This is a function i made to count number of zeroes at the end of the factorial of a number b recursively.
However i'm getting runtime error due to the used code.Pardon my naivety but any help in this would be appreciated.
int noz(int b)
{
int c=0;
int e = b;
if(e < 5)
return 0;
while(e > 0)
c = c + (e/5) + noz(e/5);
return c;
}
You are encountering "runtime error" because:
int c;
...
while(e > 0)
c = c + (e/5) + noz(e/5); // <-- HERE
you are using uninitialized local variable c, which produces undefined behavior.
You could zero-initialize this variable to prevent it happen:
int c = 0;
And also note that in case that argument of your function is greater or equal than 5, this function doesn't return anything (thanks to #Paul R for pointing this out) and another problem is that you have loop with the condition e > 0 but the loop doesn't change the value of e making it infinite loop.
Your function could look like this instead (I'm not sure what exactly is the desired logic here):
int noz(int b)
{
int c = 0;
if (b < 5)
return 0;
else
return c + (b/5) + noz(b/5);
}
//count n! tail zero
int noz(int n){
int count;
if(n < 5) return 0;
count = n / 5;
return count + noz(count);
}
Related
Is it possible to get the same results as this code using only a and b?
I'm trying to calculate c from a and b to avoid using a third variable, but I can't find a solution.
#include <stdio.h>
#include <stdlib.h>
const int LENGTH = 20;
int main()
{
char arr[LENGTH];
for (int a = 0, b = 1, c = 0; c < LENGTH; c++) {
if (a < b) {
arr[c] = '*';
a++;
} else {
arr[c] = ' ';
a = 0;
b++;
}
}
printf(arr);
return EXIT_SUCCESS;
}
Code result : * ** *** **** *****
In the event that checking if a number is triangular by linking or writing some sort of sqrt() function is not a solution that you find acceptable:
Each group of **... in the final string has a ' ' at the end, so the shortest segment in the string is "* ", which is 2 chars long.
The c in your loop is the index of the char array that this iteration should write to, the a is the index inside the current group of '*'s, and b is length of the current group of '*'s less one (since we want to count the spaces). Directly before the if clause in your for loop, it can be said that c is the sum from 2 to b plus a.
In other words, if a=0, and b=1, then c=0, because the sum from 2 to 0 is 0, plus 0 is 0.
If a=3, and b=4, then c= (2+3+4) + 3 = 12.
This means that you could write your code like this:
#include <stdio.h>
const int LENGTH = 20;
int sumFromTwo(int in){ //Recursive function to calculate sigma(2:in)
if(in < 2)
return 0;
else
return in + sumFromTwo(in - 1);
}
int main()
{
char arr[LENGTH + 1]; //Extra byte for null-terminator
for (int a = 0, b = 1; sumFromTwo(b) + a < LENGTH ; ) {
if (a < b) {
arr[sumFromTwo(b) + a] = '*';
a++;
} else {
arr[sumFromTwo(b) + a] = ' ';
a = 0;
b++;
}
}
arr[LENGTH] = '\0'; //Always null-terminate your strings
printf(arr);
return EXIT_SUCCESS;
}
But using recursion to avoid using a variable that is almost certainly going to be optimized into a register anyway is not going to save your computer any resources, least of all RAM, so it is definitely cleaner to do it the way you did in your question (but please null-terminate your string before passing it to your choice of printf or puts).
When I run the following C code I get the values:
222222222
312222222
102222222
I was expecting the values:
222222222
31
10
Why does the char number[] defined in my intToStr function remember previous values? I thought once the function call ended all local data was more or less destroyed.
#include <stdio.h>
void intToStr(int n);
int main(void)
{
intToStr(222222222);
intToStr(31);
intToStr(10);
return 0;
}
void intToStr(int n)
{
char number[10];
int l = 0;
if (n < 0)
{
l++;
number[0] = '-';
n *= -1;
}
int nCopy = n;
while (nCopy > 9)
{
nCopy /= 10;
l++;
}
int r;
while (n > 9)
{
r = n % 10;
n /= 10;
number[l--] = r + '0';
}
number[l] = n + '0';
printf("%s\n", number);
}
the array should not remember the old data
For each program, the C standard either:
specifies what the program should do
says that it is not specified what the program should do
It hardly ever says that the program should not do something in particular.
In this case, the standard says that it is not specified what characters should be in the array at the start of the function. They can be anything at all. Characters from the previous call is one particular case of "anything at all".
That's undefined behavior. If only the first 3 character are set, it may print 312222222 or it may print 312???????????????????
The last characters in char number[10] are not initialized, that means the compiler may decide to leave it alone and the old values stay, or something else happens.
Otherwise printf doesn't know where the string end, it keeps printing until it randomly hits a zero.
If there is buffer overrun printf finds a different set of characters in memory (which we are not supposed to be accessing) and the program keeps printing those same characters until it randomly hits a zero and finally stops.
To fix it, simply make sure there is '\0' at the end. You can also add additional check to make sure the length does not exceed the buffer size
Working example:
char number[10];
int l = 0;
if (n < 0)
{
l++;
number[0] = '-';
n *= -1;
}
if (n < 0) return;
int nCopy = n;
while (nCopy > 9)
{
nCopy /= 10;
l++;
}
int len = l;
if (len + 1 > sizeof(number))
return;
number[len + 1] = '\0';
int r;
while (n > 9)
{
r = n % 10;
n /= 10;
number[l--] = r + '0';
}
number[l] = n + '0';
printf("%s\n", number);
I am learning how to program in c:
I want to create a program that separates a number into digits, from there I want to store them into an array (which I've already done in the code below). From there I need to print out the number by using the digits to help with producing the same number. The program crashed upon running and I don't know why.
#include <stdio.h>
int power(int a, int b);
int main()
{
//Issue: printing out incorrect numbers
//Fix: Recall that c is treated as a character here when getchar is invoked
#define MAX_SIZE 100
const int TEN = 10;
const int ONE = 1;
int c;
int digitPos, digitHolder, numberPower = 0;
int my_strg[MAX_SIZE];
printf("\n");
while (((c = getchar()) != EOF) && (c != '\n'))
{
my_strg[digitPos] = c - '0';
digitPos = digitPos + ONE;
}
while (digitPos >= 0)
{
int toPower = digitPos - 1;
printf("%10d", power(TEN, toPower));
digitPos = digitPos - 1;
}
return 0;
}
int power(int a, int b)
{
if (b == 0)
{
return 1;
}
else
{
return a * power(a, b - 1);
}
}
Currently the output is the powers required to return the inputted number, but after the print, the program crashes. Could someone please guide me in the right direction as to how I can fix this problem?
Change the while condition while (digitPos >= 0) into while (digitPos > 0)
Because when digipos==0 --> toPower==-1 --> power(TEN, toPower) CRASH
Beside that tiny problem your code is fine
I'm trying to figure out why this code isn't working.
#include <stdio.h>
int main()
{
int num;
puts("what index of the Fibbonaci series do you want?");
scanf("%d", &num);
num = fib(num);
printf("%d", num);
return 0;
}
int fib(int num)
{
if (num == 0)
return 1;
else if (num == 1)
return 1;
else return (fib(num - 1)+fib(num-2));
}
P.S. I'm trying to keep it as simple as possible, and I was told that index's 0 and 1 are equal to 1.
Firstly, your function is not declared before main() and that is why your program does not run1.
Secondly, Fibonacci Sequence is defined as either:
1, 1, 2, 3, 5, 8,...
or
0, 1, 1, 2, 3, 5, 8,...
where the recursive relation describing it is : Fibn = Fibn-1 + Fibn-2
Which converted in C code would look like either something similar with what you got (first definition above), or a bit modified (using the second equally right definition):
int fib(int num)
{
if (num == 0) {
return 0;
} else if (num == 1) {
return 1;
} else {
return fib(num - 1) + fib(num - 2);
}
}
Note:
Both mine and your versions of the function are not very effective as they will make a lot of calls, most of them to calculate overlapping values, i.e. they will calculate a lot of overlapping subproblems. This could be fixed by using memoization.
Here is an example of an implementation, using the above notion of memoization:
// header needed for the container: map
#include <map>
int mem_fact (int i, std::map<int, int>& m) {
// if value with key == i does not exist in m: calculate it
if (m.find(i) == m.end()) {
// the recursive calls are made only if the value doesn't already exist
m[i] = mem_fact (i - 1, m) + mem_fact (i - 2, m);
}
// if value with key == i exists, return the corresponding value
return m[i];
}
int fast_factorial (int i) {
// key (Fibonacci index) - value (Fibbonaci number)
std::map<int, int> memo;
// initialize the first two Fibonacci numbers
memo.insert(std::pair<int,int>(0, 0));
memo.insert(std::pair<int,int>(1, 1));
return mem_fact(i, memo);
}
then in main,if you call both like so:
int slow_fib = fib(10);
int fast_fib = fast_factorial(10);
you will get the same result: slow_fib = fast_fib = 55, however fib() will have to make 177 calls and fast_factorial() only 19 calls.
1. error: 'fib' was not declared in this scope
fib(0) is 0, not 1. Whoever indicated/ordered that fib(0) is 1 is wrong.
Change
if (num == 0)
return 1;
to
if (num == 0)
return 0;
Best thing is to avoid recursive form as possible.
int fib(int index) -- first fibonacci number is at index 0
{
int a = 0;
int b = 1;
int c = 0;
for (int i = 0; i<index; ++i)
{
a = b;
b += c;
c = a;
}
return a; // <<-- value at index
}
UVA problem 100 - The 3n + 1 problem
I have tried all the test cases and no problems are found.
The test cases I checked:
1 10 20
100 200 125
201 210 89
900 1000 174
1000 900 174
999999 999990 259
But why I get wrong answer all the time?
here is my code:
#include "stdio.h"
unsigned long int cycle = 0, final = 0;
unsigned long int calculate(unsigned long int n)
{
if (n == 1)
{
return cycle + 1;
}
else
{
if (n % 2 == 0)
{
n = n / 2;
cycle = cycle + 1;
calculate(n);
}
else
{
n = 3 * n;
n = n + 1;
cycle = cycle+1;
calculate(n);
}
}
}
int main()
{
unsigned long int i = 0, j = 0, loop = 0;
while(scanf("%ld %ld", &i, &j) != EOF)
{
if (i > j)
{
unsigned long int t = i;
i = j;
j = t;
}
for (loop = i; loop <= j; loop++)
{
cycle = 0;
cycle = calculate(loop);
if(cycle > final)
{
final = cycle;
}
}
printf("%ld %ld %ld\n", i, j, final);
final = 0;
}
return 0;
}
The clue is that you receive i, j but it does not say that i < j for all the cases, check for that condition in your code and remember to always print in order:
<i>[space]<j>[space]<count>
If the input is "out of order" you swap the numbers even in the output, when it is clearly stated you should keep the input order.
Don't see how you're test cases actually ever worked; your recursive cases never return anything.
Here's a one liner just for reference
int three_n_plus_1(int n)
{
return n == 1 ? 1 : three_n_plus_1((n % 2 == 0) ? (n/2) : (3*n+1))+1;
}
Not quite sure how your code would work as you toast "cycle" right after calculating it because 'calculate' doesn't have explicit return values for many of its cases ( you should of had compiler warnings to that effect). if you didn't do cycle= of the cycle=calculate( then it might work?
and tying it all together :-
int three_n_plus_1(int n)
{
return n == 1 ? 1 : three_n_plus_1((n % 2 == 0) ? (n/2) : (3*n+1))+1;
}
int max_int(int a, int b) { return (a > b) ? a : b; }
int min_int(int a, int b) { return (a < b) ? a : b; }
int main(int argc, char* argv[])
{
int i,j;
while(scanf("%d %d",&i, &j) == 2)
{
int value, largest_cycle = 0, last = max_int(i,j);
for(value = min_int(i,j); value <= last; value++) largest_cycle = max_int(largest_cycle, three_n_plus_1(value));
printf("%d %d %d\r\n",i, j, largest_cycle);
}
}
Part 1
This is the hailstone sequence, right? You're trying to determine the length of the hailstone sequence starting from a given N. You know, you really should take out that ugly global variable. It's trivial to calculate it recursively:
long int hailstone_sequence_length(long int n)
{
if (n == 1) {
return 1;
} else if (n % 2 == 0) {
return hailstone_sequence_length(n / 2) + 1;
} else {
return hailstone_sequence_length(3*n + 1) + 1;
}
}
Notice how the cycle variable is gone. It is unnecessary, because each call just has to add 1 to the value computed by the recursive call. The recursion bottoms out at 1, and so we count that as 1. All other recursive steps add 1 to that, and so at the end we are left with the sequence length.
Careful: this approach requires a stack depth proportional to the input n.
I dropped the use of unsigned because it's an inappropriate type for doing most math. When you subtract 1 from (unsigned long) 0, you get a large positive number that is one less than a power of two. This is not a sane behavior in most situations (but exactly the right one in a few).
Now let's discuss where you went wrong. Your original code attempts to measure the hailstone sequence length by modifying a global counter called cycle. However, the main function expects calculate to return a value: you have cycle = calculate(...).
The problem is that two of your cases do not return anything! It is undefined behavior to extract a return value from a function that didn't return anything.
The (n == 1) case does return something but it also has a bug: it fails to increment cycle; it just returns cycle + 1, leaving cycle with the original value.
Part 2
Looking at the main. Let's reformat it a little bit.
int main()
{
unsigned long int i=0,j=0,loop=0;
Change these to long. By the way %ld in scanf expects long anyway, not unsigned long.
while (scanf("%ld %ld",&i,&j) != EOF)
Be careful with scanf: it has more return values than just EOF. Scanf will return EOF if it is not able to make a conversion. If it is able to scan one number, but not the second one, it will return 1. Basically a better test here is != 2. If scanf does not return two, something went wrong with the input.
{
if(i > j)
{
unsigned long int t=i;i=j;j=t;
}
for(loop=i;loop<=j;loop++)
{
cycle=0;
cycle=calculate(loop );
if(cycle>final)
{
final=cycle;
}
}
calculate is called hailstone_sequence_length now, and so this block can just have a local variable: { long len = hailstone_sequence_length(loop); if (len > final) final = len; }
Maybe final should be called max_length?
printf("%ld %ld %ld\n",i,j,final);
final=0;
final should be a local variable in this loop since it is separately used for each test case. Then you don't have to remember to set it to 0.
}
return 0;
}