Debugging Factorial Recursion - c

I am new to the C programming language and I am trying to learn recursion for computing the factorial of a given number. My question is the debugging printf statement is printing 2,6,24,120 if I input '5'. How does it print 4 times if the function calls are replaced with the corresponding values and computes the factorial at a time?
#include<stdio.h>
#include<stdlib.h>
int factorial(int n);
int main()
{
int num;
int fact_val;
printf("Enter the number for which you are going to compute the factorial:");
scanf("%d",&num);
fact_val=factorial(num);
printf("The factorial of the given number is %d\n",fact_val);
return 0;
}
int factorial(int n)
{
int factorial_val;
if(n==1)
return 1;
else
{
factorial_val=factorial(n-1)*n;
printf("Debugger-%d\n",factorial_val);
}
return factorial_val;
}

When you reach your base-case, you return immediately rather than printing.
So you see a printf for cases: 5, 4, 3, 2, and when the function is passed 1, the value isn't printed: you return instead.
Furthermore you recurse before you print, so the cases are printed in order, least-first: the first print happens only after you've recursed all the way down to 2. Hence you see: 2, 6, 24, 120. Only when you've returned from the current recursion is the intermediate value printed.
Write down the recursion to make it clearer:
5 -> recurse with 4:
4 -> recurse with 3:
3 -> recurse with 2:
2 -> recurse with 1:
1 -> base case, just return...
printf (1 * 2) = 2;
printf (2 * 3) = 6;
printf (6 * 4) = 24;
printf (24 * 5) = 120;

Related

In C, computing an equation using user input values is not giving the expected result?

I am doing an assignment for my class but I am stuck. The assignment is to:
Write a recursive program to precompute Fibonacci numbers and store them in an array. Fibonacci formula is Fib(0) = 1, Fib(1) = 1 and Fib(i) = Fib(i − 1) + Fib(i − 2). Store the ith Fibonacci number at index i. Have a loop to read i and print i and ith Fibonacci number. Use −1 to quit the loop. My output is wrong but I don't know how to fix it. I have been trying for a while now but I just couldn't pinpoint my mistake.
My code is
#include <stdio.h>
double Fib[50]; //globally declared
int fib(int i)
{
for(i=0; i<50; i++) //loop to scan
{
scanf("%lf", &Fib[i]); //scan and store numbers in an array
if (Fib[i]==-1) //i =-1 will end loop
break;
}
Fib[i]= Fib[i-1]+Fib[i-2];//formula
if(Fib[i]==0||Fib[i]==1) //i=0 and i=1 will print 1
Fib[i]=1;
else if(i>1) //performs the operation with the formula
printf("%d %lf\n", i, Fib[i]);
}
int main()
{
int i=0;
fib(i);
return 0;
}
Expected result:
user input: 4 10 20 15 5 -1
output:
4 5.000000
10 89.000000
20 10946.000000
15 987.000000
5 8.000000
My output:
5 20.000000
A couple points:
Your program isn't recursive
Compute all of Fib first with your recursive function then after
handle user input in a loop
The code below has the structure for dealing with user input, do the recursion:
#include <stdio.h>
// It would make sense for this to store unsigned long long instead of double
// because Fibonacci numbers are always positive integers
unsigned long long Fib[50];
// Your assignment specifically said use a recursive program to compute Fib.
// This is not a recursive function, but it is correct, I will leave the
// recursion for you to work out
void populateFib() {
Fib[0] = 1;
Fib[1] = 1;
unsigned i;
for (i = 2; i < 50; ++i)
Fib[i] = Fib[i - 1] + Fib[i - 2];
}
int main() {
// First compute Fib
populateFib();
// Deal with user input in an infinite loop
for (;;) {
int input;
scanf("%d", &input);
// Condition for breaking the infinite loop
if (input == -1)
break;
// Sanity check the user won't read out of bounds
if (input < 0 || input >= 50) {
printf("No!\n");
continue;
}
// Display what the user wants
printf("%d %llu\n", input, Fib[input]);
}
return 0;
}

Why is my pthread program missing prime numbers?

I am working on a program that utilizes pthreads in C. The function of the thread is to compute prime numbers based on a maximum number entered by the user at the CLI. Thus say for instance, the user enters ./ComputePrimes 20, the output should be 2, 3, 5, 7, 11, 13, 17, 19.
However, for some reason, my program only outputs 2 to 13 (thus my output is 2, 3, 5, 7, 11, 13).
I am using a formula based off of Wilson's Theorem for computing primes:
https://en.wikipedia.org/wiki/Formula_for_primes
I know from a Discrete Mathematics class I have taken in the past that there is no solid formula for computing primes. The purpose of this program however is to demonstrate pthreads which I believe I have done successfully. Here is my program:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *generatePrimeNumbers(void *primenum) {
int i, j, a, b;
int primeNumbers[] = {};
int limit = (int *)primenum;
for (i = 1; i <= limit; i++) {
j = 0;
int a = (factorial(i) % (i + 1));
int b = (i - 1) + 2;
if (((a / i) * b) != 0) {
primeNumbers[j] = ((a / i) * b);
printf("%d ", primeNumbers[j]);
j++;
}
}
printf("\n");
return NULL;
}
int factorial(int n) {
if (n == 1) {
return 1;
} else return n * factorial(n - 1);
}
int main(int argc, char *argv[]) {
int numLimit;
pthread_t primethread;
if (argc != 2) {
printf("You need to enter a valid number!\n");
exit(-1);
}
else {
int i = 0;
numLimit = atoi(argv[1]);
if (numLimit < 2) {
printf("Please enter a number greater than or equal to 2.\n");
exit(-1);
}
}
pthread_create(&primethread, NULL, generatePrimeNumbers, (void *)numLimit);
pthread_exit(NULL);
}
As you can see below, I successfully create a thread, however some of the prime numbers are missing. I believe that I might have messed up somewhere in my called threads function. Thanks!
In many environment, int can only store integers only upto 2147483647 (2**31 - 1) while 20! = 2432902008176640000. Therefore, factorial(20) cannot be calculated correctly.
Making the return type of factorial to long long will make the output for input 20 correct (supposing that long long can save upto 2**63 - 1), but for larger number, you should consider other method such as taking modulo inside factorial method before the number gets too big.
Also note that the line
int limit = (int *)primenum;
looks weird. The cast should be int, not int *.
Another point is that you are assigning numbers to 0-element array as Retired Ninja said.
In this code, primeNumbers isn't used other than the printing point, so the printing should be done directly like
printf("%d ", ((a / i) * b));

Can you reverse the total? (Looping C)

"can you reverse the number" is the number already reverse by using Mod(%). My question, can it be reversed to normal?
For example, if you enter the number "2552" it'll change to "2+5+5+2", which is correct, but, when you enter another number like "4125" it will change to "5+2+1+4" instead of "4+1+2+5"
Ok, I just entered the programming world, a newcomer
With the "if" can it add "+" without exceeding the number like "4+1+2+5+"
there are "+" after "5", how can I delete this extra "+"?
#include <stdio.h>
main(){
int a, b, h=0;
printf("Enter the number : ");
scanf("%d",&a);
printf("%d = ", a);
while(a != 0)
{
b=a%10;
a=a/10;
printf("%d",b);
if(b != a)
{
printf("+");
}
h=h+b;
}
printf(" = %d\n", h);
}
Instead of scanning for an actual number, you can scan a string from the user. Strings are easy to reverse:
char num[5]; // Has the input
char rev[5]; // Will have the reverse
int len = strlen(num);
rev[len] = 0; // End the string
for(int i = 0; i < len; i++){
rev[i] = num[len-i-1];
}
You can go backwards by taking the highest digits in your number first instead of the lowest, e.g. like so:
int currentLog10;
int powerOfTenForCurrentDigit;
...
while(a != 0)
{
currentLog10 = (int)log10(a);
powerOfTenForCurrentDigit = (int)pow(10, currentLog10);
b = a/powerOfTenForCurrentDigit;
a = a - b * powerOfTenForCurrentDigit;
...
}
How does it work:
log10 of 4125 will give us 3.
b is set to 4125 devided by 1000 (10^3) = 4.
a is set to 4125 - 4 * 1000 = 125
Next step log10 of 125 gives 2, we devide by 10^2 (100) and so on.
Last step 5 gives 0, 5 devided by 10^0 (1) gives 5, a becomes 5 - 5 * 1, which is 0, we are done.
You have to be careful in edge cases, where log10 returns something like (n-1).999999999 instead of n, but it shouldn't happen for small numbers as are entered in your program. Maybe add some sanity check for the input.

How to fix program printing a 0 after the print statement executes in C?

This program tests Goldbach's Conjecture, printing a given even integer as the sum of two primes. After printing the first one, the given integer is to iterate by 2 , then find the sum of two primes for that integer. And so on until the program is interrupted by the user.
This problem is that the program prints a '0' after every executed print statement.
The code:
#include <stdio.h>
#include <math.h>
int GC(int goldsum); //function prototype
int main()
{
int goldsum;
printf("Enter an even integer greater than 5: ");
scanf("%d", &goldsum);
printf("%d\n", GC(goldsum));
goldsum = goldsum + 2;
printf("%d\n", GC(goldsum));
}
int GC(int goldsum) //function definition
{
int i, j; //prime addends
int div1, div2; //divisors
char prime1, prime2;
for (i=2 ;i<goldsum ;i++) //when number is less than goldsum, run this loop iterating by 1
{
prime1 = 1;
for (div1=2 ;div1<i ;div1++) //this loop determines if "i" is prime.
if (i % div1 == 0) //if yes, the prime number is stored in "i"
prime1 = 0;
if (prime1)
{
for (j=3; j<goldsum; j+=2) //when number is less than goldsum, run this loop iterating by 2
{
prime1 = 1;
for (div2=2; div2<j; div2++) //this loop determines if "j" is prime.
if(j % div2 == 0) //if yes, the prime number is stored in "j"
prime1 = 0;
if (prime1)
if (i + j == goldsum) //If i + j = goldsum, it prints the result.
{
printf("%d + %d = %d\n",i ,j , goldsum);
return 0;
}
}
}
}
return 0;
}
The output:
Enter an even integer greater than 5: 10
3 + 7 = 10
0
5 + 7 = 12
0
What I want it to look like:
Enter an even integer greater than 5: 10
3 + 7 = 10
5 + 7 = 12
use just GC(goldsum);
instead of printf("%d\n", GC(goldsum));
Maybe you misunderstood the return 0; we put in main(). Every function has to return the value we desire. In the case of main we want 0 because that means everything was OK. In the case of your function the return value should be what YOU want from it.
Edit: re-read the question and adding this: Since you don't want a return value from you function you should declare it as void and not have it in a printf() because all the printing you want is in your function.
Void functions do not return a value, so that is what you want.

Recursion, possible error in algo

i am doing one of the simple programin C, sum of digits of 5 digit number.Though i had done it using a simple function but i need to do it with recursion also.I had read many solution on net regarding this problem using recursion and had implemented one of mine.But that is giving error and i cant figure out what mesh i am doing in my algo.
#include<stdio.h>
int sum5(int x); //function for sum of digits of 5 digit number
int main()
{
int x;
int result;
printf("Enter a 5 digit number : ");
scanf("%d",&x);
printf("Number entered by you is %d",x);
result = sum5(x);
printf("Sum of digits of 5 digit number is = %d",&result);
return 0;
}
int sum5(int x)
{
int r;
int sum=0;
if(x!=0){
r=x%10;
sum=sum+r;
x=x-r; //doing this so that 0 come in the last and on diving it by 10, one digit will be removed.
sum5(x/10);
}
return sum;
}
but after its execution i am getting wrong result.It is dumping some anonymous value on the output.
Also, your sum5 function is incorrect. You have to add the value of sum5 to the sum variable of the caller function.
int sum5(int x)
{
int r;
int sum = 0;
if (x != 0) {
r = x % 10;
sum = r;
//x = x - r; - this isn't required. integer division will floor x
sum += sum5(x / 10);
}
return sum;
}
This is incorrect as it is printing the address of result and not its value:
printf("Sum of digits of 5 digit number is = %d",&result);
Change to:
printf("Sum of digits of 5 digit number is = %d", result);
Always check the result of scanf() to ensure a valid value was read:
/* Returns number of assignments made. */
if (scanf("%d", &x) == 1 && x > 9999 && x < 100000)
{
}
Plus the error in the implementation of sum5() as pointed out by Osiris
.

Resources