Help me to find the sum of this series x^1+x^4+x^7+.. to n terms
#include<conio.h>
#include<math.h>
int main(int argc, char const *argv[]) {
int n;
float x;
int l=1;
printf(" Enter the value of x :");
scanf("%f",&x);
for (int i = 1; i <=n; i++)
{
l = pow(x,l+3);
}
printf("x ^ %d + power %d",x,l);
return 0;
}
I think this is what you want :) i've commented the errors
#include<conio.h>
#include<math.h>
int main(int argc, char const *argv[]) {
int n;
float x;
float l=0,i=0;
// initialize n first to determine how far the sum should go
printf(" Enter the value of n :");
scanf("%d",&n);
printf(" Enter the value of x :");
scanf("%f",&x);
for (int i = 0; i <n; i++)
{ //l+= pow(x,(i*3)+1); is equivilant to l= l+ pow(x,i+3); which i assume that's what you wanted to do
// l should be a float as well not int since x is a float
l+= pow(x,(i*3)+1);
if(i!=n-1)printf(" %f^%d +",x,i*3+1);
else printf("%f^%d",x,i*3+1);
}
printf("\nResult of the sum is %f",l);
return 0;
}
There's a problem in this loop:
for (int i = 1; i <=n; i++)
{
l = pow(x,l+3);
}
You set l every time and then in the end it has the value of the last assignment, but you wanted to add them all up. Also, it should be i in the pow call, not l+3, instead you should move that step of 3 to the loop increment. Try this:
int l = 0;
for (int i = 1; i <= n; i+=3)
{
l += pow(x, i);
}
Also make sure that you initialize n, you should probably read it in using scanf, just like you do with x.
Also note that since l is int, it's going to be truncated every time. If you don't want that, you should declare it as float instead, and depending on how precise the result should be, you might even want to consider double.
#include <stdio.h>
#include <math.h>
int main()
{
double x;
unsigned n;
fprintf(stderr, "enter x and n :");
/* enter x as a double and x as an unsigned number, both on the same line, and check 2 values are enter */
if (scanf("%lg %u", &x, &n) != 2)
puts("invalid or missing values");
else {
double r = 0; /* sum initialization */
int p = 1; /* the power to apply, 1 then 4 then 7 etc */
while (n--) { /* have to sum n times */
r += pow(x, p); /* x^1+x^4+x^7+... */
p += 3; /* next power value */
}
printf("%g\n", r);
}
return 0;
}
if I well understand n terms x^y must be added rather than the last pow is x^n, I use double for x and of course the result ( r )
Executions :
enter x and n :1.2 3
6.85678
enter x and n :2 1
2
Check with bc :
% bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
scale=6
1.2 + 1.2^4 + 1.2^7
6.856780
Multiple operations on floating point numbers tend to compound rounding errors very quickly, so if you can minimize the number of operations, always do.
Now if you recognize that your polynomial is a Geometric series (see wikipedia article) with a = x and r = x^3, then we have the following pseudo-code algorithm (note no loops!):
Case 1 (x == 0): Sum == 0 regardless of n.
Case 2 (x == 1): Sum == n.
Case 3 (x any other number): Sum == x*(1-(x^(3*n)))/(1-(x^3)).
Case 4 (n==infinity and -1<x<1): Sum == x/(1-(x^3)).
I trust you can code accordingly.
Related
Hello im new to C programming and this is my C Quiz question.
I tried really hard but i cant find the solution or whats wrong with my code.
This equation block cant work.
Any help will be appreciated
Write a C program that displays the below menu and performs the
corresponding operation, according to the selected menu item.
Write separate functions for each menu item and call the related function according to the
selection.
The menu:
(1) Calculate fibonacci value of the entered number,
(2) Calculate the equation (Get value of R from the user),
(3) Get four numbers from the user, sort them in ascending order
Enter your choice:
When the user enters a number (1, 2 or 3) corresponding function will be called
to perform the operation.
The user will enter -1 if he wants to continue and the
menu will be appeared on the screen again.
Question Equation Pic
#include <stdio.h>
#include <stdlib.h>
int fibonacci(int numForFibonacci)
{
int i = 0;
int j = 1;
int k = 1;
for (int b = 1; b <= numForFibonacci; b++)
{
k = i + j;
printf("%d \n", i);
i = j;
j = k;
printf("%d ", k);
}
printf("\n");
return k;
}
float theEquation(float numR)
{
float multipl, result = 1;
for (int i = 1; i <= numR; i++)
{
multipl = (2i + 4) / (i * i);
result *= multipl;
}
printf("Result is %f", result);
return result;
}
int ascending(int n)
{
int k = 0, i = 0, j = 0, number[4];
for (int w = 0; w < n; w++)
scanf("%d", &number[w]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
k = number[i];
number[i] = number[j];
number[j] = k;
}
}
}
for (i = 0; i < n; ++i)
printf("\n%d \n", number[i]);
return i;
}
int main()
{
int choice, choiceFibo;
float choiceR;
do
{
printf("[1]Fibonacci calculation\n");
printf("[2]calculating the equation: (2k+4)/(k*k)\n");
printf("[3]sorting numbers in ascending order\n");
scanf("%d", &choice);
if (choice == 1)
{
printf("enter a number for fibonacci\n ");
scanf("%d", &choiceFibo);
fibonacci(choiceFibo);
}
else if (choice == 2)
{
printf("[2]enter a number for (2k+4)/(k*k)\n");
scanf("%f", &choiceR);
theEquation(choiceR);
}
else
{
printf("[3]enter four numbers to sort them in ascending order\n");
ascending(4);
}
printf("If you want to do another calculation enter '-1'.\n");
scanf("%d", &choice);
} while (choice == -1);
return 0;
}
TL;DR: Two main issues:
<integer>i in GNU C represents a complex number, not multiplication.
integer division is not what you'd expect
Your issue lies on this line:
multipl = (2i + 4) / (i * i);
You might think that 2i would evaulate as 2 * i, but in C, 2i is a complex int.
This can be seen here:
#include <stdio.h>
int main()
{
int i=1;
printf("%d", 2i);
return 0;
}
You would expect this to print 2, but instead we get a warning.
Compiled with onlinegdb:
warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘complex int’
Second issue: Integer division. The other answer already covered it pretty well, but for the sake of self-contained answers:
In C, integer division finds the integer solution and discards the remainder.
2/5 = 0
6/5 = 1
10/5 = 2
10/4 = 2
10.0 / 4 = 2.5
(double)10/4 = 2.5
You need to "type coerce" one of the values in your numerator or denominator to a float/double, which will coerce the entire fraction to a float/double.
You can do this either with 2.0*i or (double)2*i. Either one works, but the second one is more explicit for readability.
To fix the issue, simply change 2i to (double)2*i.
There are only three edits required to get a clean compile:
Change int main() to int main(void)
Change (2i + 4) / (i * i) to (2*i + 4) / (i * i)
Change int ... number[4]; to int ... number[4]={0};
If you did not see something similar to the following upon your compile, then turn on all warnings:
> s0_15.c - 4 warnings
> 28, 28 warning: implicit conversion discards imaginary component: '_Complex int' to 'float'
> 45, 17 warning: variable 'number[i]' may be uninitialized when used here
> 38, 5 note: variable 'number' is declared here
> 54, 27 warning: variable 'number[i]' may be uninitialized when used here
> 38, 5 note: variable 'number' is declared here
> 58, 5 warning: function declaration isn't a prototype.
To ensure accurate calculations, see integer division addressed in another answer under your post.
I was assigned a Hw that required me to calculate the value of e via using the series:
1 + 1/1! + 1/2! + ...1/n!
The value of e must be calculated until the value of n (entered by the user) is reached. Also, the value of 1/n! must be calculated until it's value is smaller than epsilon (also entered by the user).
I wrote the code, but there are some errors that compiler is telling me errors such as relational comparisons, use of ';' etc. Could anyone please help me fix the error. Thank you in advance.
Below is my code:
#include<stdio.h>
int factorial (int i)
{
if (i==0)
return 1;
else
return i*factorial(i-1);
}
int main(void) {
int i,n;
float e,ep;
printf("what is the value of epsilon: ");
scanf("%f",&ep);
printf("what is the value of n: ");
scanf("%d",&n);
for (i=1; i<=n, i++)
e= 1+1/factorial(i);
for(1/fatorial(i)<=ep)
printf("The value of e for the entered value of epsilon and n:%f",e);
return 0;
}
For more precision I would use double instead of float.
for (i=1; i<=n, i++)
e= 1+1/factorial(i);
This is wrong, you are not adding to e, you are assigning always the last
value of the series, which is always 0 (except for i = 1). So your e will
always be 1.
factorial is a function that returns an int. A int divided by an int is
an int and in C anything 1/x (for x > 1, x integer) is 0. You you to use
1.0 or cast at least one of the arguments to double (or float if you are
using floats):
double e = 1; // initializing e
for(i = 1; i <= n; ++i)
e += 1.0/factorial(i);
Also, the value of 1/n! must be calculated until it's value is smaller than epsilon, also entered by the user.
I don't understand what that means, if n is a fixed value given by the user,
what do you keep calculating? Is this really what the exercise says?
My interpretation would be: if by n steps |e_real - e_calculated| > epsilon,
keep incrementing n, otherwise stop. That would be
#include <stdio.h>
#include <math.h>
#include <stdint.h>
uint64_t factorial (uint64_t i)
{
if (i==0)
return 1;
else
return i*factorial(i-1);
}
int main(void)
{
int n;
double e = 1;
double epsilon;
printf("what is the value of epsilon: ");
scanf("%lf", &epsilon);
printf("what is the value of n: ");
scanf("%d",&n);
int i = 1;
while(1)
{
e += 1.0/factorial(i++);
if(i >= n && (fabs(e - M_E) < epsilon))
break;
}
printf("e: %.20lf, calculated e: %.20lf, error: %.20lf, steps: %d\n", M_E, e, fabs(e-M_E), i);
return 0;
}
Note: if you are using GCC, you have to compile it with the -lm option:
$ gcc e.c -oe -lm
You're not summing the series but actually set e to 1.
Because you set it to e + 1/factorial(n) but your factorial() returns an int which is very likely to be above 1, so the division is integral, and 1 divided by any greater number will give 0.
The last loop is very strange. Did you mean while rather than for? Note that factorial is mistyped. Moreover, no work is done in the loop's body other than printing the same message over and over.
I need to write a C program which will read a number (in base 10) from user input and output it in any base which is a power of 2. The calculations have to be performed in one function, to_base_n, which takes the parameters num and base and prints the number in the respective base. As a validation check, the program also checks if the base is a power of two with the isPowerofTwo function.
The way the conversion is carried out is by means of long division which carries out the logic in the pseudocode below:
void to_base_n(int x, int n){
int r, i = 0
int digits[16]
while (x ≠ 0){
r = x mod n
x = x / n
digits[i] = r
i++
}
for (i = 0, i < 15, i++)
print digits[i]
}
Which I believe is arithmetically sound. But when I try to, for example, convert 82000 to base 4, I get the following output:
The large digits appearing are even bigger than num itself, so I figured the modulus cannot be entering the array properly (because ∀{x,n}; x mod n < x). I can't seem to find what's wrong with it. The full code is listed below.
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
bool isPowerofTwo(int);
void to_base_n(int, int);
int main(){
//Variables
int num, base;
//Prompt
printf("Please enter a number in base 10: ");
scanf("%d", &num);
printf("Please enter a base (2^n) to convert it to: ");
scanf("%d", &base);
//Precaution
while(!isPowerofTwo(base)){
printf("That number is not a power of 2. Please try again: ");;
scanf("%d", &base);
}
if(isPowerofTwo(base)){
//Output
printf("The number %d (base 10) is equivalent to ", num);
to_base_n(num, base);
printf(" (base %d).", base);
}
//Return Statement
return 0;
}
//Checks if Base is a Power of Two
bool isPowerofTwo(int base){
while((base % 2 == 0) && base > 1){
base = base / 2;
if(base == 1){
return true;
break;
}
}
return false;
}
//to_base_n
void to_base_n(int x, int n){
int r, i = 0;
int digits[16];
while(x != 0){
r = x % n;
x = x / n;
digits[i] = r;
i++;
}
for(i = 0; i < 15; i++)
printf("%d|",digits[i]);
}
Can anyone help explain what's wrong with it?
The number 82000 in base 4 would be:
110001100
Which is exacly what you get. Your mistake is that:
They are printed backwards.
You are printing more digits than you should, so you print garbage.
You ignore the number of digits extracted with your pseudo code, so you print uninitialised elements of the array.
for (i = 0, i < 15, i++)
print digits[i]
And they are printed in reverse order. I suggest changing it to this
for (i = i - 1, i >= 0, i--)
print digits[i]
and as C code in your function
for(i = i - 1; i >= 0; i--)
printf("%d|",digits[i]);
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
.
This is what I came up with:
#include <stdio.h>
int main (void)
{
int n, i, j;
float e = 1.0, nFact = 1.0;
printf ("please enter the number");
scanf ("%d", &n);
for (i = 1; i <= n ; i++)
{
for (j = 1; j <= i; j++)
{
nFact *= j;
}
e = e + (1.0 / nFact);
}
printf ("The value of 'e' is : %f", e);
return 0;
}
This is what I get from this code.
Input: 3
Output: 2.58333 (which is close to 2.6666...)
But for n=3, e should give 2.6666.. as a value.
Am I doing something wrong here? How can I get the proper output?
You are needlessly calculating the factorial in every iteration. Just replace the inner loop by nFact *= i;.
#include<stdio.h>
int main (void)
{
int n,i,j;
float e=1.0, nFact=1;
printf("please enter the number");
scanf("%d", &n);
for( i =1; i<= n ; i++)
{
nFact*=i;
e = e + (1.0/ nFact);
}
printf("The value of 'e' is : %f", e);
return 0;
}
Am i doing something wrong here?
You have forgotten to set the factorial variable to one. So, your variable is getting smaller quickly. This makes (1.0/nFact) even smaller and that is why you get smaller e.
nFact=1.0; //add this line so it resets to 1.0 everytime a factorial is needed
for( j = 1 ; j <= i; j++)
{
nFact *= j;
e = e + (1.0/ nFact);
}
//only single loop is more than enough
You are getting your factorial by O(n) complexity. Why not save the old value and use it in every iteration?(O(1)--->no need the factorial-loop. Just use old value since you are not resetting it. (Just multiply by i)
how can i get the proper output?
After the 11st or 12th iteration, your float would not give enough precision-resolution-minimum step. Double or BıgDecimal seems better if your going for science.
That loop is very inefficient: Note how your inner loop computes the same thing over and over!
Instead, you should keep a running term and update it:
double term = 1;
double result = term;
for (unsigned int i = 1; i != n; ++i)
{
term /= i;
result += term;
}
printf("With %u steps we compute %f.\n", n, result);