0

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);
  • [`pow`](https://en.cppreference.com/w/c/numeric/math/pow) is a floating point function, and as such have the same problems as all floating point arithmetic have on computers and is discussed in [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) For integers I suggest you make up your own function instead, but beware of overflows. – Some programmer dude Dec 29 '18 at 09:46
  • It's an assignment before functions so i didin't use functions,thanks for your answer – muhammed kartal Dec 29 '18 at 09:50
  • Also please read about [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Edit your question to give us the *full* input that makes it fail, and tell us the expected and actual output. – Some programmer dude Dec 29 '18 at 09:50
  • 1
    For `a=5` and `n=5` the result is `30517578125` which is too large for a 32-bit `int`. Try `double sum = 1;` and `printf("%f",sum);` – Weather Vane Dec 29 '18 at 10:04
  • 1
    You can avoid calling `pow`, by calculating one power from the previous power: a^n = a^(n-1) * a – Damien Dec 29 '18 at 10:07

2 Answers2

0

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.

H.S.
  • 11,654
  • 2
  • 15
  • 32
0

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;
}
0___________
  • 60,014
  • 4
  • 34
  • 74