Idea is this: http://prntscr.com/m0xopk , It works perfectly except 5, when i give 5 it calculates wrong.I can't understand why?
int i,a,n;
int sum = 1;
scanf("%d",&a);
scanf("%d",&n);
for(i = 1;i <= n;i++){
sum *=pow(a,i);
}
printf("%d",sum);
It works perfectly except 5, when i give 5 it calculates wrong
No, it works perfectly for values less than 5. When you give input 5 for both a and n, the summation resultant number will be 30517578125 which is big for 32 bit int type variable to hold. Instead, you should use uint64_t type variable.
Also, you should not use pow() function for integer type. Check this.
You can do:
#include <stdio.h>
#include <inttypes.h>
int main()
{
int i, a, n;
uint64_t num = 1, result = 1;;
printf ("Enter a: \n");
scanf("%d",&a);
printf ("Enter n: \n");
scanf("%d",&n);
for(i = 0;i < n;i++){
num = num * a;
result = num * result;
}
printf("result: %"PRId64"\n", result);
return 0;
}
Note that this 64 bit solution is also having a limit and will work for input 5 but may not be for a number little bigger than 5. If you want arbitrarily large number, check this.
Integers cant accommodate so large numbers. You need to use float numbers instead.
double calc(double a, int i)
{
double sum = 1;
for(int p = 1; p <= i; p++)
{
sum *= pow(a,i);
}
return sum;
}
Related
Sum of numbers occurring in the multiplication table of 8. What's wrong with my code? Desirable output is 440, and I'm getting 33204.
#include <stdio.h>
int
main ()
{
int sum, n, p;
printf ("Sum of numbers occurring in the multiplication table of 8: ");
do
{
p = 8 * n;
sum += p;
n++;
}
while (n <= 10);
printf ("%d", sum);
return 0;
}
You are using uninitialized variables
int sum, n, p;
that have indeterminate values.
As a result your program has undefined behavior.
You need to initialize them like
int sum = 0, n = 1, p;
Please initialize n first. Attaching my code for reference here:Code and ouput attached
Just initialize the variable as:
int sum = 0, n = 1, p;
Because you have not initialized the varaible, they are taking garbage value which is bydefault stored to them and that's why they are giving you a this kind of answer.
Now run the below code and you will get 440 as your answer.
#include <stdio.h>
int
main ()
{
int sum = 0, n = 1, p;
printf ("Sum of numbers occurring in the multiplication table of 8: ");
do
{
p = 8 * n;
sum += p;
n++;
}
while (n <= 10);
printf ("%d", sum);
return 0;
}
How to write a program in c that gets single integer and another integer that is more than 3 digits at least and after that the single integer goes to the left side of the three digits number and the right side as well.
Note: I need help for the left side right side number
For example:
I mean if I got 5 and 100
it should be 51005
something like this:
int a = 5, b = 100;
int length = 1;
int tmp = b;
while (tmp /= 10)
length++;
int left = 10;
for (int i = 0; i < length; i++)
left *= 10;
int result = (left * a) + (10 * b) + a;
std::cout << result;
Also, you can play here.
there are so many methods :
one is stated in the reply above by #MikeCAT .
int a = 5, b = 100; printf("%d%d%d\n", a, b, a);
you can also try to transfer them to strings , contact them and put it back as an int if you're asked to have a variable named as c using itoa and atoi with a very static manner
char string[100],string1[100],string2[210];
int a,b,c;
scanf("%d %d",&a,&b);
itoa(a,string,10);
itoa(b,string1,10);
string2 = string+string1+string;
c=atoi(string2);
printf("Your number %d",c);
you can also try to think about it mathematically
int a,b;
scanf("%d %d",&a,&b);
int x=b,i=0,c=a;
while (x!=0) { // to get the length of b
i++;
x= x/10; }
int j ;
for (j=1;j<i;j++)
c=c*10;
c=c+b+a;
printf("your number is %d",c);
etc etc
This factorial function starts giving wrong results with 13 and above. I have no idea why.
#include <stdio.h>
int fatorial (int p);
int main() {
int x = 13;
int test = fatorial(x);
printf("%d", test);
}
int fatorial (int p) {
if (p <= 0)
return 1;
else
return p*fatorial(p-1);
}
for x = 0, 1, 2 ...12 it prints the right result, but for 13! it prints 1932053504 which is not correct.
For x=20 it prints -210213273 for example.
I know that this is not the best way to do a factorial. Its my homework tho, it HAS to be this way.
If you try this you will get the maximum value that int can hold:
#include <stdio.h>
#include <limits.h>
int main(void)
{
printf("%d\n", INT_MAX);
}
Your code causes overflow.
You could get a few more numbers if you use a bigger type, but not by very much. You could use this:
unsigned long long fatorial (unsigned long long p) {
if (p <= 0)
return 1;
else
return p*fatorial(p-1);
}
It won't get you far though. If you want bigger than that you need to find a library for bigger integers or create some custom solution. One such library is https://gmplib.org/ but that is likely out of scope for your homework.
And btw, a condition like p <= 0 is not good. It indicates that the factorial of a negative number is always one, which is false.
It is because after 12, the result of factorial of any number exceeds the size of int.
you can try the following code:
#include<stdio.h>
int main()
{
int a[100],n,counter,temp,i;
a[0]=1;
counter=0;
printf("Enter the number: ");
scanf("%d",&n);
for(; n>=2; n--)
{
temp=0;
for(i=0; i<=counter; i++)
{
temp=(a[i]*n)+temp;
a[i]=temp%10;
temp=temp/10;
}
while(temp>0)
{
a[++counter]=temp%10;
temp=temp/10;
}
}
for(i=counter; i>=0; i--)
printf("%d",a[i]);
return 0;
}
The result of the function is too big. I think big int would work better for your purposes. Big int allows you to have bigger numbers. Also, this is what I would do.
int x = the number you want to factorialize
int ans = 1;
(Then instead of all of those functions)
for(var i = x; i > 0; i--) {
ans = ans*i;
}
System.out.println(ans);
Javascript link: https://jsfiddle.net/8gxyj913/
I need to get to 100!
100! is about 9.332622e+157. Simply using standard integer types is insufficient. 32-bit int is good to 12!. With 64-bit integer math, code could get to about 21!
Could use floating point math and give up precision.
Instead consider a string approach.
Trying to learn C I'm toying around a bit with some for loops and sums. I want to compute the sum of the first n natural numbers without using the mathematical formula n(n+1)/2. I have this code for it:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 100;
int sum = 0;
for (int ix = 0; ix <= n; ix++) {
sum = sum + ix;
}
printf("Sum of the first %d natural numbers is %d\n", n, sum);
}
So for n = 100 I get the sum to be 5050, which is correct. I also get correct when I use n = 10000, however if I go for example n = 1000000 then I get the sum = 1784293664 but correct answer should be sum = 500000500000.
Why does my program stop working when n becomes larger and what is that number of the sum being displayed when n = 1000000?
If you want to calculate a sum of natural numbers then instead of the type int use the type unsigned int.
Correspondingly declare the variable sum as having the type unsigned long long int to decrease the risk of overflow.
For example
unsigned int n = 100;
unsigned long long int sum = 0;
for ( unsigned int ix = 1; ix <= n; ix++){
sum = sum + ix;
}
printf("Sum of the first %u natural numbers is %llu\n" , n, sum);
Or you could include the header <inttypes.h> and use the type uintmax_t for the variable sum as it is shown in the demonstrative program below.
#include <stdio.h>
#include <inttypes.h>
int main(void)
{
unsigned int n = 1000000;
uintmax_t sum = 0;
for ( unsigned int ix = 1; ix <= n; ix++){
sum = sum + ix;
}
printf("Sum of the first %u natural numbers is %" PRIuMAX "\n" , n, sum);
return 0;
}
The program output is
Sum of the first 1000000 natural numbers is 500000500000
Pay attention to that there is no need to introduce the auxiliary variable ix. The loop can look simpler as for example
#include <stdio.h>
#include <inttypes.h>
int main(void)
{
unsigned int n = 1000000;
uintmax_t sum = 0;
while ( n ) sum += n--;
printf( "Sum of the first %u natural numbers is %" PRIuMAX "\n" , n, sum );
return 0;
}
You are hitting variable type 'int' limit. Try using long data type to store the sum.
int type is too small to contain numbers so huge, so an arithmetic overflow happens on the way up there. What you observe is called undefined behaviour (UB for short), this is what officially happens in C when signed integers overflow (unsigned ones simply rollover to zero and on).
#include<stdio.h>
int main(){
int i=0, sum=0, n=10;
while(i<=n){
printf("%d\n",i);
sum=sum+i;
i++;
}
printf("%d",sum);
return 0;
}
I have been struggling with this code and just do not seem to grasp what I am doing wrong.
The code is suppose to calculate : Sum of a series of "Cosine" with pattern [(-1)^i(x)^2i]/(2i)!
Here is my code thus far:
#include <stdio.h>
#include <math.h>
float factorial(int n){
if (n==0)
return 1;
else
return 2*n*factorial(n-1);
}
int main (){
float i, n;
float sum=0;
printf("Enter desired interger: ");
scanf("%f", &n);
for (i=0; i<=1; i++)
sum = sum + (pow(-1,i)*pow(n,2*i))/(factorial(n));
printf("The value is %f\n", sum);
return 0;
}
I still working on it, any info or help will be much appreciated!
edit:
Just fixed it guys, this is new format I had to use for my professor:
#include <stdio.h>
#include <math.h>
int factorial(int n)
{
if (n==0) return 1;
else
return n*factorial(n-1);
}
float mycos(float x)
{
float sum=0;
int i;
for (i=0;i<=10;i++) sum = sum + (pow(-1,i)*pow(x,2*i))/factorial(2*i);
return sum;
}
int main()
{
int i=1;
printf(" x mycos(x) cos(x)\n");
for (i=1;i<=10;i++)
printf(" %f %f %f\n", i*.1, mycos(i*.1), cos(i*.1));
return 0;
}
Thank you all for your explanations, they helped out Immensely!
One thing I see, is that your for loop within main only runs through 2 real iterations, once for i == 0, and again for i == 1.
For the taylor expansion to work fairly effectively, it needs to be run through more sequence terms (more loop iterations).
another thing I see, is that your denominator is the n! rather than (2 * n)!
For efficiency, I might also implement the factorial routine as follows:
unsigned int factorial(int n){
unsigned int product = 1;
for(int I = 1; I <= n; I++) product *= I;
return product;
}
The above factorial routine is for a more EXACT factorial calculation, which perhaps you don't need for this purpose. For your purposes, perhaps the floating point variant might be good enough.
float factorial(int n){
float product = 1;
for(int I = 1; I <= n; I++) product *= (float)I;
return product;
}
I should also note why I am stating to perform factorial in this manner. In general a loop construct will be more efficient than its recursive counterpart. Your current implementation is recursive, and thus the implementation I provide SHOULD be quite a bit more efficient from both performance, and memory utilization.
Considering computation expense, you need to stop calculating the series at a point. The more you go, the more precise the result will be, but the more your program spends time. How about this simple program:
#include <stdio.h>
#include <math.h>
#define ITERATIONS 10 //control how far you go
float factorial(int n){
if (n==0)
return 1;
else
return n*factorial(n-1);
}
int main (){
float n;
float sum=0;
printf("Enter desired float: ");
scanf("%f", &n);
int c, i;
for (i=0; i<=ITERATIONS; i++) {
c = (i%2)==0? 1 : -1;
sum = sum + (c*pow(n,2*i+1))/(factorial(2*i+1));
}
printf("The value is %f\n", sum);
return 0;
}
1.) You are only multiplying even no.s in factorial function return 2*n*factorial(n-1); will give only even no.s. Instead you can replace n with 2n here- sum = sum + (pow(-1,i)*pow(n,2*i))/(factorial(2n)); This will give the correct (2n!).
2.) Check for the no, of iterations for (i=0; i<=1; i++) this will only run your loop twice. Try more no. of iterations for more accurate anwer.
Why are you calculating power etc for each item in the series? Also need to keep numbers in a suitable range for the data types
i.e. for cos
bool neg_sign = false;
float total = 1.0f;
float current = 1.0f;
for (int i = 0; i < length_of_series; ++i) {
neg_sign = !neg_sign;
current = current * (x / ((2 * i) + 1)) * (x / (( 2 * i) + 2));
total += neg_sign ? -current : current;
}
EDIT
Please see http://codepad.org/swDIh8P5
#include<stdio.h>
# define PRECISION 10 /*the number of terms to be processed*/
main()
{
float x,term=1,s=1.0;
int i,a=2;
scanf("%f",&x);
x=x*x;
for(i=1;i<PRECISION;i++)
{
term=-term*x/(a*(a-1));
s+=term;
a+=2;
}
printf("result=%f",s);
}
Your factorial() function actually calculates 2n.n!, which probably isn't what you had in mind. To calculate (2n)!, you need to remove the 2* from the function body and invoke factorial(2*n).