Recursion in C: why does my simple code doesn't work? - c

Given i the value of 3, the output should be the sum of 3/(3+1) + 2/(2+1) + 1/(1+1), always stopping on 1.
I can't seem to figure out what's wrong with what I did, thank you for your attention.
#include <stdio.h>
#include <math.h>
int sum_recur(int i) {
if (i > 1) {
return sum_recur(i - 1) / (sum_recur(i - 1) + 1);
} else {
return 1;
}
}
int main(void) {
int i;
printf("Inform a number:\n");
scanf("%d", &i);
printf("%d \n", sum_recur(i));
}

I think this would be the right recursive implementation of your formula
int sum_recur(int i){
if(i >= 1){
return (i / (i + 1)) + sum_recur(i-1);
} else{
return 0;
}
}
Also, as #atirit mentioned, you should consider making the output to be float or double in order to preserve the floating points values of the division result. Otherwise, the result of sum_recur will always be 0 since i / (i + 1) is always 0 for integer type
#include <stdio.h>
#include <math.h>
float sum_recur(int i){
if(i >= 1){
return (i / (i + 1.0)) + sum_recur(i-1);
} else{
return 0;
}
}
int main(void){
int i;
printf("Inform a number:\n");
scanf("%d",&i);
printf("%f \n",sum_recur(i));
}

Here's what I believe you're trying to implement, no need for recursion, but it's there if you need it:
#include <stdio.h>
double sum_recur(double i) {
if (i < 1) return 0;
return i / (i + 1) + sum_recur(i - 1);
}
double sum_iter(double i) {
double sum = 0;
for (; i >= 1; i--) {
sum += i / (i + 1);
}
return sum;
}
int main(void) {
int i;
printf("Inform a number:\n");
scanf("%d", &i);
printf("%f \n", sum_iter((double) i));
printf("%f \n", sum_recur((double) i));
}
The summary is this:
There's no need for the math library.
Use float or double and not int - in the code itself and in the printf.
Correct the logic in the recursion.
It can be solved iteratively quite nicely.

I don't understand what are you trying to achieve from this code. The code that you've written will always return 2.
sum_recur will always stop at 1 and you return statement will calculate 1/1+1, which is always 2. For input 3, the sum_recur will generate following:
sum_recur reaches 1 and hence returns 1 for input value 2
1/1 + 1 = 2, so for i=2 sum_recur will again return 2
This is will go on for any input number. This is why no matter what the input is, output of this recursion will always be 2. Further, what you expect this function to do in your question statement is not possible if you're using division between recursion calls. The result that you're looking to achieve is simply addition of 2 n-times or multiplication of 2 with n.

The answers written here explain the problem reasonably well, I just want to add a little bit on your code specifically,
While you do f(i-1)/f(i-1)+1 this is a terrible way of doing this and in case of a larger seed input this might cause you runtime problem with stackoverflow. So I suggest you should try something that's more efficient if at all you have to use recusion. Like this by storing the fun call value
int n = f(i-1);
return n/n +1;

Related

Factorial as a sum of consecutive number

I was recently solving a problem "No. of ways to express factorial of a number as sum of consecutive number"
My solution is :
int fact_as_sum(int n) { // n is the number whose factorial need to be taken
long int fact=1;
int temp=0,count=0;
for(int i=n;i>0;i--){
fact*=i;
}
printf("%d\n",fact);
for(int i=fact/2;i>0;i--) {
int j=i;
temp=fact;
while(temp>=0) {
if(temp==0) {
count++;
break;
}
else
temp-=j;
j--;
}
}
return count;
}
The solution works correct till small no. of 10!.
But my solution has high complexity.
Can anyone suggest a less complex solution ?
Thanks
Ok, so this problem tickled my brain a lot, so first of all thank you for that, I love to solve these kind of problems!
I started with a math analysis of the problem in order to find the best implementation, and I came up with this solution:
By defining n as the factorial result number, m the number of sums to be performed and x the starting number for the addition, it all breaks down to the following formula:
.
This can now be simplified, resulting in the following formula:
.
That can be also simplified, giving the following result:
.
Solving for x (the starting number for addition), results in:
.
It is now possible to iterate for all the values of m to find the wanted x value. the lower bound for m is for sure 0, it is not possible to add a negative quantity of numbers! The top bound can be found by noticing that x should be a positive number, it would have no sense to consider negative values that will be nulled by the corresponding positive part! This gives the following result:
That yields the following result:
The negative value of m is discarded as previously said.
This translates in the following C code:
#include <stdio.h>
#include <math.h>
void main() {
int fact = 8; //select the wanted factorial to compute
float n = 1;
int i;
float x;
float m;
printf("calculating %d factorial...\n", fact);
for (i = 2; i < fact + 1; i++) {
n *= (float)i;
}
printf("the factorial result is %d\n", (int)n);
printf("calculating the sum of consecutive numbers...\n");
//compute the maximum number of iterations
int maxIter = (int)((-1 + sqrt(1 + 8 * n)) / 2);
for (i = 0; i < maxIter; i++) {
m = (float)i;
//apply the formula
x = (n / (m + 1)) - (m / 2);
if (x - (float)((int)x) == 0) {
printf("found a correct sum!\n");
printf("the starting number is: %d\n", (int)x);
printf("the number of sums is: %d\n", i + 1);
}
}
}
I've tried this solution on a couple of values and wrote the code for the test, the results seem right. There is an issue with the factorial though, since the factorial reaches very high values quickly, memory needs to be managed better.
Hope I gave an interesting solution, I had fun solving it!
Please correct in case there are problems with this solution.
Sure. I may try and give a simpler solution for finding the count: replace
temp = fact;
while(temp>=0) {
if(temp==0) {
count++;
break;
}
else
temp-=j;
j--;
}
by
if ( fact % j == 0 )
count++;
. This also means you don't need temp, since you can use the remainder operator (%) to check for whether j is a divisor (that's what you tried to do in that while loop, right?).
Fist of all, your code has a bug.
1. You need to change i=fact/2 in for loop to i=(fact+1)/2;
2. You need to add j > 0 condition in while loop to prevent infinite loop. Because for example temp-(-1) will increment temp.
Fixed code:
for(long int i=(fact+1)/2; i>0; i--) {
long int j=i;
temp=fact;
while(j > 0 && temp > 0) {
temp-=j;
j--;
if(temp == 0) {
count++;
break;
}
}
}
As of your question, it can be done in O(sqrt(2*N)) time. Here are some understandable, clean answers:
long int count = 0;
for (long int L = 1; L * (L + 1) < 2 * fact; L++) {
float a = (1.0 * fact-(L * (L + 1)) / 2) / (L + 1);
if (a-(int)a == 0.0)
count++;
}
https://www.geeksforgeeks.org/count-ways-express-number-sum-consecutive-numbers/
https://math.stackexchange.com/questions/139842/in-how-many-ways-can-a-number-be-expressed-as-a-sum-of-consecutive-numbers

c program to find average

i am a beginner in coding ,i am trying to make a program where i input 'n' number of elements in array and find out what percentage of number are positive,negative and zeros.the output is not what i am expecting it is all 'zeros'.Where i input n=3,so the percentage should be .3,.3,.3 when i input numbers one positive,one negative and one zero.
#include <math.h>
#include <stdio.h>
int main()
{
int n;
float per1, per2, per3;
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
for (int i = 0; i <= n - 1; i++)
{
if (arr[i] < 0)
{
int sum1 = sum1 + 1;
}
if (arr[i] > 0)
{
sum2 = sum2 + 1;
}
else
{
sum3 = sum3 + 1;
}
}
per1 = sum1 / n;
per2 = sum2 / n;
per3 = sum3 / n;
printf("%.6f\n%.6f\n%.6f\n", per1, per2, per3);
return 0;
}
output
3
1
-2
0
0.000000
0.000000
0.000000
the last three numbers should be .3,.3,.3 but it is giving zeros.
I think this code is a little bit better. I've used the function malloc() instead of the "scattered" declaration int arr[n] (in this case I prefer the old C style).
People already said you the problem relevant to the variable types and some ways to solve the problem. Here there's another way similar to the others you just saw between the answers.
#include <math.h>
#include <stdio.h>
#include <malloc.h>
#define STR_ORD_SUFFIX(i) (i>3)?"th":(i==0)?"--":(i==1)?"st":(i==2)?"nd":"rd"
int main()
{
int n, *arr=NULL;
float per1,per2,per3;
int sum1=0;
int sum2=0;
int sum3=0;
printf("How many number you have to insert? ");
scanf("%d",&n);
if (n<=0)
return 1;
arr=malloc(n*sizeof(*arr));
if (arr==NULL)
return 2;
printf("Insert %d number%c\n",n,(n!=1)?'s':'\x0');
for(int i = 0; i < n; i++){
printf("%4d%s: ",i+1,STR_ORD_SUFFIX(i+1));
scanf("%d",&arr[i]);
}
for(int i=0;i<=n-1;i++)
{
if(arr[i]<0){
sum1=sum1+1;
} else if(arr[i]>0){
sum2=sum2+1;
} else {
sum3=sum3+1;
}
}
per1=sum1; per1/=n; per1*=100.0;
per2=sum2; per2/=n; per2*=100.0;
per3=sum3; per3/=n; per3*=100.0;
printf("\n<0 %.6f%%\n>0 %.6f%%\n=0 %.6f%%\n",per1,per2,per3);
if (arr!=NULL)
free(arr);
return 0;
}
Do floating point arithmetic like this
per1=sum1/(1.0*n);
per2=sum2/(1.0*n);
per3=sum3/(1.0*n);
How do you calculate percentage of some value? Your answers shouldn't be 1,1,1 but 33%, 33%, 33% for input you have. So your code should instead of this
per1=sum1/n;
be like this
per1=sum1*100.0/n;
And you have also got wrong your if conditions. The else part is tied only to second if. So every number less or equal to 0 is counted into sum3 which is not what you probably meant. So your
if (arr[i] > 0)
should have been
else if (arr[i] > 0)
And one last thing. On this line you are creating completely new variable sum1 that will live only to the end of the if statement and thus will not appear in the final calculation. I will leave it to you how to fix it.
int sum1 = sum1 + 1;
I don't know what environment you are using for development, but you should learn how to use debugger from the beginning. You can then peek into flow of your code to see what is going on and when it went wrong. With simple programs like this it is really easy. If you are on Visual Studio, they have really nice debugger integrated. Just set breakpoint and run Debug. If you are on Linux, there is gdb which might come pretty rough for beginners, but there are also graphical tools like ddd.
Since both sum1 and n are integers, the result of sum1/n is also an integer. This means that if sum1 is less than n, then the result of sum1 / n is 0.
To get a floating point result, at least one of the operands has be be float or double. I suggest you declare your sum variables to be double instead of int.

Reverse two numbers and obtain the reverse of the sum

I am coming to SO as a last resort. Been trying to debug this code for the past 2 hours. If the question is suited to some other SE site, please do tell me before downvoting.
Here it goes:
#include <stdio.h>
#include<math.h>
int reverse(int n) {
int count = 0, r, i;
int k = (int)log(n * 1.0);
for(i = k; i >= 0; i--)
{
r = (n % 10);
n = (n / 10);
count = count + (r * pow(10, k));
}
return count;
}
int main(void) {
int t;
scanf("%d", &t);
while(t--)
{
int m, n, res;
scanf("%d %d", &m, &n);
res = reverse(m) + reverse(n);
printf("%d", reverse(res));
}
return 0;
}
My objective is to get 2 numbers as input, reverse them, add the reversed numbers and then reverse the resultant as well.I have to do this for 't' test cases.
The problem: http://www.spoj.com/problems/ADDREV/
Any questions, if the code is unclear, please ask me in the comments.
Thank you.
EDIT:
The program gets compiled successfully.
I am getting a vague output everytime.
suppose the 2 numbers as input are 24 and 1, I get an output of 699998.
If I try 21 and 1, I get 399998.
Okay, if you had properly debugged your code you would have notices strange values of k. This is because you use log which
Computes the natural (base e) logarithm of arg.
(took from linked reference, emphasis mine).
So as you are trying to obtain the 'length' of the number you should use log10 or a convertion (look at wiki about change of base for logarithms) like this: log(x)/log(10) which equal to log10(x)
And now let's look here: pow(10, k) <-- you always compute 10^k but you need 10^i, so it should be pow(10, i) instead.
Edit 1: Thanks to #DavidBowling for pointing out a bug with negative numbers.
I don't know how exactly you have to deal with negative numbers but here's one of possible solutions:
before computing k:
bool isNegative = n < 0;
n = abs(n);
Now your n is positive due to abs() returning absolute value. Go on with the same way.
After for loop let's see if n was negative and change count accordingly:
if (isNegative)
{
count = -count;
}
return count;
Note: Using this solution we reverse the number itself and leave the sign as it is.
It looks like Yuri already found your problem, but might I suggest a shorter version of your program? It avoids using stuff like log which might be desirable.
#include <stdio.h>
int rev (int n) {
int r = 0;
do {
r *= 10;
r += n % 10;
} while (n /= 10);
return r;
}
int main (void) {
int i,a,b;
scanf("%d",&i);
while (i--) {
scanf("%d %d",&a,&b);
printf("%d\n",rev(rev(a) + rev(b)));
}
return 0;
}
Hopefully you can find something useful to borrow! It seems to work okay for negative numbers too.
Under the hood you get char string, reverse it to numeric, than reverse it to char. Since is more comfortable work with chars than let's char:
char * reverse (char *s,size_t len) //carefull it does it in place
{
if (!len) return s;
char swp, *end=s+len-1;
while(s<end)
{
swp =*s;
*s++=*end;
*end--=swp;
}
return s;
}
void get_num(char *curs)
{
char c;
while((c=getchar())!='\n')
*curs++=c;
*curs=0;
}
int main()
{
double a,b,res;
char sa[20],sb[20],sres[20],*curs;
get_num( sa);
get_num(sb);
reverse(sa,strlen(sa));
reverse(sb,strlen(sb));
sscanf(sa,"%f",&a);
sscanf(sb,"%f",&b);
res=a+b;
sprintf(sres,"%f",res);
reverse(sres);
printf(sres);
}

How do you write factorial in C?

I need to input this equation and there's a factorial in it. I would like to know if there was something like * = multiplication or pow(1,3) for factorial of something in C.
term = pow(-1, K) * pow(x, 2K)/(2K)
The factorial would be for the last 2K.
Rarely you need a function for computing factorials. Factorials grow so fast that a look-up-table is sufficient for the few values for which the computation does not overflow. If you are computing terms in a loop, you can avoid computing the factorial using an accumulator for the entire term.
K = 0;
term = 1;
while (K<N) {
/* use term */
do_something_with(term);
/* update term for new value of K */
K += 1;
term = -term * x*x / (2*K*(2*K-1));
}
If that seems unclear to you, you can first derive this program where the accumulators are explicit, and then combine the update step into a single variable like above. This program will still have problems with the factorial computation blowing up.
K = 0;
pow_minus_1_K = 1;
pow_x_2K = 1;
factorial_2K = 1;
while (K<N) {
/* compute term */
term = pow_minus_1_K * pow_x_2K/factorial_2K;
/* update accumulators for new value of K */
K += 1;
pow_minus_1_K = -pow_minus_1_K;
pow_x_2K *= x*x;
factorial_2K *= 2*K*(2*K-1);
}
Factorials are easy to calculate, after all n! is just the product of all numbers up to n. But there is a practical problem: Factorials overflow pretty quickly. A 32-bit int can hold 12!, a 64-bit int 20!.
Depending on how your series converges, you might overflow the valid range.
With approximation series like yours, it is usually better to find a means to represent term k by means of term k − 1. In your case:
term = pow(-1, k) * pow(x, 2*k) / fact(2*k)
you can represent a term as
term[k + 1] = -term[k] * pow(x, 2) / ((2*k - 1) * (2*k - 2))
and your series becomes:
double f(double x)
{
double term = 1.0;
double res = term;
int k = 0;
while (k < 100) {
double old = res;
term = -term * (x / (2*k + 1)) * (x / (2*k + 2));
res += term;
if (res == old) break;
k++;
}
return res;
}
This function will use at most 100 iterations to calculate the cosine. It stops when the term doesn't contribute to the result. In practice, it reaches the result with about 10 iterations, so in that case the regular factorial calculations would have been accurate enough. Still, calculating them over and over is wasteful.
There is no predefined function for factorial, but it can be recursively implemented as follows.
int factorial( int a )
{
if ( 0 == a )
return 1;
else
return a * factorial( a - 1 );
}
People who like the ? operator might implement the function as follows.
int factorial( int a )
{
return 0 == a ? 1 : ( a * factorial( a - 1 ) );
}
If a non-recursive formulation is desired, the implementation can be done as follows.
int factorial( int a )
{
int Result = 1;
for ( int i = a; i > 0; Result *= i, i-- );
return Result;
}
If for some reason recursive functions leave you scratching your head, you can also implement it without recursion:
/* calculate n factorial */
unsigned long long nfact (int n)
{
if (n <= 1) return 1;
unsigned long long s = n;
while (--n)
s *= n;
return s;
}
(note: it is up to you to you to implement a test for overflow, if desired)
I think using recursion for this problem is a good way to get started with recursion and understand the way it works, but it's not efficient enough since you're calling a function every time. If you want to know why, do a test and see how long it takes. Although I should say, the iterative method is not significantly better either.
From Code Complete by Steve McConnell:
Don't use recursion for factorials or Fibonacci numbers
One problem with computer-science textbooks is that they present silly
examples of recursion. The typical examples are computing a factorial
or computing a Fibonacci sequence. Recursion is a powerful tool, and
it's really dumb to use it in either of those cases. If a programmer
who worked for me used recursion to compute a factorial, I'd hire
someone else.
So when keep that in mind when going over the recursive versions that are posted here. Now, how to write one.
Basically you have a base case for when the number is less than 1, and a general recursive case. You generally have a base case and a recursive case in a recursive function. For a factorial, it would look something like this:
int factorial_rec(int number)
{
if (number == 0)
{
return 1;
}else
{
return number * factorial_rec(number - 1);
}
}
long fact(int num)
{
if(num==0)
return 1;
else
return num*fact(num-1);
}
Include the above code and call this method to get factorial of a number.
The code to find factorial of a given number using recursive algorithm can be as shown below :
#include<stdio.h>
int fact(int n)
{
if(!n)
return 1;
else
return (n*fact(n-1));
}
void main()
{
int n;
printf("Enter number : ");
scanf("%d",&n);
printf("\nFactorial of %d is : %d",n,fact(n));
}
#include<stdio.h>
long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
void main()
{
int number;
long fact;
printf("Enter a number: ");
scanf("%d", &number);
fact = factorial(number);
printf("Factorial of %d is %ld\n", number, fact);
return 0;
}
#include<stdio.h>
int main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++){
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
return 0;
}
#include <stdio.h>
int main() {
int n, i;
unsigned long long fact = 1;
printf("Enter an integer: ");
scanf("%d", &n);
// shows error if the user enters a negative integer
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else {
for (i = 1; i <= n; ++i) {
fact *= i;
}
printf("Factorial of %d = %llu", n, fact);
}
return 0;
}

|c| Series 1+2x+3x^2+4x^3+....nx^(n-1)

First of all, I searched and all questions I found are similar but not exactly this one.
This is my first post here, I'm a beginner in programming and currently learning to code in C.
Been struggling with this code for about 5 hours now.
The question is create a program in C, using only loops (and not using pow(), using stdio.h library only).
The question is to get the user to give you two numbers - X and N
the program will print The result of the following equation:
1+2x+3x^2+4x^3+....+nx^(n-1)
For example for the input of - X=2 N=3
1*2^0 + 2*2^1 + 3*2^2
What the program will print is "17"
This is my attempt so far, I got to the Power function but I cant find a way to incorporate into the programm itself.
#include <stdio.h>
int main(void)
{
int i, j=0, b = 0;
float x, n;
double sum = 0, sumt=0;
do{
printf("Please enter two numbers \n");
flushall;
scanf("%f %f", &n, &x);
} while (x <= 0);
for (i = 1; i <= n; i++){
sum = x*x;
}
sumt += sum;
printf("%f", sum);
}
Instead of trying to create an implementation of pow, you will need to take advantage of the relationship between the terms of the expression.
The n-th term is nx^(n-1). The n-1-the term is (n-1)x^(n-2).
If we denote the n-th term as T(n) and denote the n-1-th term as T(n-1),
T(n) = T(n-1)*x*n/(n-1)
Given the starting value of the first term,
T(1) = 1
you can compute the subsequent terms using the above formula.
The following code should work.
// Initialize the values for N=1
term = 1;
sum = 1;
// Iterate starting from 2
for (i = 2; i <= n; i++){
term *= x*i/(i-1);
sum += term;
}
The working Program based on the tips given by the almighty #R_Sahu (And others ;D)
**
#include <stdio.h>
int main(void)
{
int i, j = 0, c = 0;
float x, n, b = 0;
double term, sum;
do {
printf("Enter Two Numbers\n");
flushall;
scanf("%f%f", &n, &x);
} while (x < 0);
for (i = 2; i < n + 2; i++)
{
term = 1;
sum = 1;
for (i = 2; i <= n; i++){
term *= x*i / (i - 1);
sum += term;
}
}
printf("The answer is %.lf ", sum);
}
I will not give you the code, but the reasoning you should follow
First you have to somehow get the data from the user (as a parameter, from stdio... whatever)
x = getFromUser
n = getFromUser
You will then need to init a temporary result
result = 0
How many times do you have to add? -> Exactly n times
for(ii=0;ii<n;ii++) {
result = result + pow((ii*x),(ii-1)) //There is something missing here, I'll let you guess what
}
But wait; you cannot use pow. So you have to program it by yourself (I guess that's the idea of the exercise)
then you need a function, and it has to return an int (actually, it may return even irrational numbers, but I don't think they will require you to do that)
int customPow(int base, int exponent) {
//Put your for in here, and may the pow be with you
}
You need to figure out the code yourself, but the general idea is as follows:
Create your own pow function which returns x*n.
int pow(int x, int n){
//use a for or while loop to calculate x (*x)n times.
//pay attention to the base cases (i.e., when n = 0, or 1 etc)
}
ans = 0;
for(i = 0 to N-1){
ans = ans + pow(x,i-1)*i;
}

Resources