How to calculate iterative and recursive solutions? - c

Following needs to be calculated (iterative und recursive Solution)
Sum = 1 – 1/2 + 1/3 – 1/4 + - . . . 1/n (n > 0) with float reihe (int n)
We have the following so far:
#include <stdio.h>
float reihe(int n)
{
float sum = 0;
if (n = 1)
sum = 1;
else
{
for (int i = 1; i < n; i++)
{
sum += (1 / i) - (1 / (1 + i));
}
}
return sum;
}
int main(void)
{
float z;
z = reihe(5);
printf("%d", z);
return 0;
}
Would appreciate any of your help. Have a good day.

What about something like this? Not tested, but it compiles and runs...
BTW/ take a close look at the use of 1.0. If you use 1 it is interpreted as an integer and not a float and you division is always rounded to 1 or 0 and you lose all decimal values...
float reihe(int n)
{
float sum = 0;
float base = 1.0;
for (int i = 1; i <= n; i++) {
if ( i % 2 ) {
sum += base/i;
}
else {
sum -= base/i;
}
}
return sum;
}

Related

Miscalculation of Lagrange interpolation formula for higher degree

I am approximating Runge’s function using Lagrange’s interpolation formula for 50 interpolation points. I have written the following program to do this, but I am getting the wrong value for x= -0.992008. That wrong value is 4817543.091313, but it should be 5197172.55933613. I have got this value from the following link: Link The code used are as follows:
#include <stdio.h>
#include <math.h>
double
runge(double x)
{
return (1 / (1 + (25 * x * x)));
}
double
ab(double x)
{
if (x < 0)
return -1 * x;
return x;
}
double
lag_func(double x, double *y_i, double *x_i, int n)
{
double ex = 0.0;
for (int i = 0; i <= n; i++) {
double numer = 1.0,
denom = 1.0,
prod = 1.0;
for (int j = 0; j <= n; j++) {
if (i != j) {
numer = (x - x_i[j]);
denom = (x_i[i] - x_i[j]);
prod *= numer / denom;
}
}
ex += (prod) * y_i[i];
}
return ex;
}
int
main()
{
int n;
scanf("%d", &n);
double y_i[n + 1],
x_i[n + 1];
for (int i = 0; i < n + 1; i++) {
x_i[i] = ((2 * (double) i) / (double) n) - 1;
y_i[i] = runge(x_i[i]);
}
printf("%lf\n", lag_func(-0.992008, y_i, x_i, n));
return 0;
}
The web site is rounding its Runge coefficients to six digits. Given the magnitudes of the terms involved, up to 3.9978•1011, this introduces multiple errors up to around 2•105.
This can be seen by inserting y_i[i] = round(y_i[i] * 1e6) / 1e6; after y_i[i] = runge(x_i[i]);. Then the output of the program is 5197172.558199, matching the web site’s inaccurate result.
The web site is wrong; the result of the code in the question is better.

i wrote a code for sum of series but i am not getting any output

The question was to add first seven terms of the following series using for loop
1/1! + 2/2! + 3/3! ....
I thought i might be loosing decimal point due to int but i am not even getting wrong answer.
I ran the code in terminal but it just keeps running no output.
Thanks for helping out.
#include<stdio.h>
int main()
{
int n;
float a;
float v=0.0;
for(n=1;n<=7;n++)
{
a=1.0;
while(n>0)
{
a=a/n;
n--;
}
v=v+n*a;
}
printf(" sum is %f ",v);
return 0;
}
#include <stdio.h>
int fact(int n) {
int product = 1;
for (int i = 1; i < n+1; i++) {
product *= i;
}
return product;
}
int main() {
double sum = 0.0;
for(int i = 1; i < 7+1; i++) {
sum += double(i) / fact(i);
}
printf("Sum is %f\n", sum);
return 0;
}
The series is 1/1! + 2/2! + .. n terms can be written as 1 + 1/1! + 1/2! + 1/3! + ...(n-1) terms .
So it is 1 + sum of 1/i! where i=1 to i=n-1 terms.
So I have taken sum=1 as initial value.
#include <stdio.h>
//this is the function for calculating n!
int fact(int n) {
int product = 1;
for (int i = 1; i < n+1; i++) {
product *= i;
}
return product;
}
int main() {
int n=5;
//we are taking sum=1 as initial value
double sum = 1.0;
//now we run 1/1! + 1/2! + 1/3! + 1/4! i.e. upto (n-1) terms (here n=5 => so n-1 = 4)
for(int i = 1; i < n; i++)
{
sum += (1.0) / fact(i);
}
printf("Sum is %f\n", sum);
return 0;
}
As #DeBARtha mentioned in the original code i was incrementing and then decreasing n causing to loop to run repeatedly.
By using one more variable (m) for the while loop and then decreasing it while increasing the 'n' in the for loop the problem gets resolved.
#include<stdio.h>
int main()
{
int n,m;
float a;
float v=0.0;
for(n=1;n<=7;n++)
{
m=n;
a=1.0;
while(m>0)
{
a=a/m;
m--;
}
v=v+n*a;
}
printf(" sum is %f ",v);
return 0;
}

Find the sum of a mathematical series

Write a program in C to find the sum of the series [ 1-X^2/2!+X^4/4!- .........]
Test Data:
Input the Value of x :2
Input the number of terms : 5
Expected Output:
the sum = -0.415873
Number of terms = 5
Here is the code I wrote, no compilation error, I just wasnt getting the answer right:
#include <stdio.h>
#include <math.h>
int main()
{
float sum=0;
float ans;
int c, y, fac=1;
int a,i, x=2;
float z;
for (i = 1; i<=2; i++)
{
a= 2*i;
y = pow(2,a);
for (c = 1; c<=a; c++)
{
fac= fac*c;
}
z = (float) y/fac;
if (i%2 == 0) {
sum = sum + z;
}
else{
sum = sum - z;
}
}
ans = 1 + sum;
printf("The answer is %f" , ans);
return 0;
}
You didn't used number of terms.
You didn't set fac to 1 to the end of the for.
y is equal to pow(x,a) not pow(2,a).
Int can store numbers between -2,147,483,648 and 2,147,483,647, so I recommend to use long long (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807). And also, double instead of float. You can take a look here for more details: https://learn.microsoft.com/en-us/cpp/cpp/data-type-ranges?view=msvc-160.
Here is the code:
#include <stdio.h>
#include <math.h>
int main()
{
double sum=0;
double ans;
long long c, y, fac=1;
long long a,i, x=2, numberOfTerms = 5;
float z;
for (i = 1; i<= numberOfTerms; i++)
{
a= 2*i;
y = pow(x,a);
for (c = 1; c<=a; c++)
{
fac= fac*c;
}
z = (double) y/fac;
if (i%2 == 0) {
sum = sum + z;
}
else{
sum = sum - z;
}
fac = 1;
}
ans = 1 + sum;
printf("The answer is %f" , ans);
return 0;
}
Try to use functions.
If you do not have to, do not use float. Use double for floating point calculations.
Your code does not reflect the formula at all.
double fact(unsigned n)
{
double result = 1.0;
for(unsigned x = 1; x <= n; x++)
result *= x;
return result;
}
double series(double x, unsigned nterms)
{
double result = 1;
for(unsigned term = 1; term <= nterms; term++)
{
result += (1.0 - ((term & 1) << 1)) * pow(x, (double)term * 2.0) / fact(term * 2);
}
return result;
}
int main(void)
{
for(unsigned nterms = 2; nterms < 20; nterms++)
{
printf("nterms = %2u series(4) = %.32f\n", nterms, series(4.0, nterms));
}
}
https://godbolt.org/z/8c3xM4

Program in C , working with 3 digits but not working with 5 digits

145 = sum of 1! + 4! + 5!. I need to write a program in C, that finds the 5 digit numbers that have this property.
I have written the code successfully for the 3 digits. I used the same code for 5 digits, but it cant find any number.
I would like to help me with my solution, in order for me to see where am I wrong.
#include <stdio.h>
int factorial(int n);
main() {
int pin[5];
int q = 1;
int w = 0;
int e = 0;
int r = 0;
int t = 0;
int result = 0;
int sum = 0;
for (q = 1; q <= 9; q++) {
for (w = 0; w <= 9; w++) {
for (e = 0; e <= 9; e++) {
for (r = 0; r <= 9; r++) {
for (t = 0; t <= 9; t++) {
pin[0] = q;
pin[1] = w;
pin[2] = e;
pin[3] = r;
pin[4] = t;
int factq = factorial(q);
int factw = factorial(w);
int facte = factorial(e);
int factr = factorial(r);
int factt = factorial(t);
sum = factq + factw + facte + factr + factt;
result = 10000 * q + 1000 * w + 100 * e + 10 * r + t * 1;
if (sum == result)
printf("ok");
}
}
}
}
}
}
int factorial(int n) {
int y;
if (n == 1) {
y = 1;
} else if (n == 0)
y = 0;
else {
y = n * factorial(n - 1);
return y;
}
}
Your factorial function doesn't return a value in all cases:
int factorial (int n) {
int y;
if (n==1) {
y = 1;
}
else
if (n==0)
y = 0;
else {
y = n * factorial(n-1);
return y;
}
}
It only returns a value when it makes a recursive call. The base cases don't return anything. Failing to return a value from a function and then attempting to use that value invokes undefined behavior.
Move the return statement to the bottom of the function so it gets called in all cases. Also the value of 0! is 1, not 0.
int factorial (int n) {
int y;
if (n<=1)
y = 1;
else
y = n * factorial(n-1);
return y;
}
Also, when you find the target value you probably want to print it:
printf("ok: %d\n", result);
dbush's answer is accurate in pointing out why your code didn't work. This is an alternative solution to reduce the amount of calculation done by your program by not re-calculating the factorial of each numeral every step of the way. The way your program currently works, it winds up being around 500,000 calls to the factorial function from your nested loop, and then in turn recursively calls the function on average 4ish times for each call from the nested loop, so that's around 2 million calls to factorial. The more digits you tack on, the faster that number grows and more expensive it gets. To avoid all these recalculations, you can create a Look-up table that stores the factorial of the numerals [0-9] and just looks them up as needed.
You can calculate these values ahead of time and initialize your LUT with these values, but if hypothetically you wanted them to be calculated by the program because this is a programming assignment where you can't cut out such a step, it is still pretty trivial to populate the LUT.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
void populate_lut(uint32_t *lut);
int main(void) {
// lut is an array holding the factorials of numerals 0-9
uint32_t lut[10];
populate_lut(lut);
for (uint8_t q = 1; q <= 9; q++) {
for (uint8_t w = 0; w <= 9; w++) {
for (uint8_t e = 0; e <= 9; e++) {
for (uint8_t r = 0; r <= 9; r++) {
for (uint8_t t = 0; t <= 9; t++) {
// now instead of calculating these factorials, just look them up in the look-up table
uint32_t sum = lut[q] + lut[w] + lut[e] + lut[r] + lut[t];
uint32_t result = 10000 * q + 1000 * w + 100 * e + 10 * r + t * 1;
if (sum == result) {
printf("Solution: %" PRIu32 "\n", result);
}
}
}
}
}
}
}
// populate your lookup table with the factorials of digits 0-9
void populate_lut(uint32_t *lut) {
lut[0] = 1;
lut[1] = 1;
for(uint8_t i = 2; i < 10; ++i) {
lut[i] = lut[i-1] * i;
}
}

Problem with loop in C

i'm trying to compute "2^0 + 2^1 + 2^2 + ... + 2^14", using the following program(i'm a newbie and can only compute a exponent by multiply itself a certain times). The result should be 32767, but i ran it and got 270566475, i thought for long but can't figure out why...
#include <stdio.h>
int main(void)
{
int i, e, exponent, sum;
e = 1;
exponent = 1;
sum = 1;
for (i = 1; i <=14; i++)
{
for (e = 1; e <= i; e++)
{
exponent *= 2;
}
sum += exponent;
}
printf("%d\n", sum);
return 0;
}
So what's wrong with this??? Thanks!!!
You don't need the inner loop. Just execute exponent *= 2 once, directly inside the outer loop. BTW, I think you have to do it after the sum += ....
Also, you could start with sum = 0 and i = 0, which is closer to the math you described.
Look at your inner loop by itself. It's trying to calculate, for one specific value of i, 2^i.
But exponent does not start at 1 every time. So you go into that loop with exponent already some very large value.
for (i = 1; i <=14; i++)
{
exponent = 1;
for (e = 1; e <= i; e++)
{
exponent *= 2;
}
sum += exponent;
}
Now you've reset exponent (which, to be clear, isn't the exponent at all but the calculated result) for each new power of 2.
If you have right to create a function it better to do it like this with a recursive function :
#include <stdio.h>
int power(int x, int exp) {
if (exp == 0)
return 1;
else
return x * power(x, exp-1);
}
int main (int argc, const char * argv[])
{
int i;
int sum = 0;
for (i = 0; i <= 14; i++) {
sum += power(2, i);
}
printf("%d",sum);
return 0;
}
I hope it helps.
You just need one loop because each you already have the result of n-1 value. I had correct your code it works.
#include <stdio.h>
int main (int argc, const char * argv[])
{
int i, e, exponent, sum;
e = 1;
exponent = 1;
sum = 1;
for (i = 1; i <= 14; i++)
{
exponent *= 2;
sum += exponent;
}
printf("%d\n", sum);
return 0;
}
Both codes work

Resources