0

I'm learning C function construction and I'm trying to make an exponent function with two arguments: base & exponent.

#include <stdio.h>
#include <stdlib.h>


int power(int a,int b){

    int c;
    int i;
    c=1;

    for(i=1;i<=b;++i){
        c=c*a;
    }
    return c;
}

int main(){

    int nice=power(5,20);
    printf("answer =%d , and size is=%d ", nice, sizeof(nice));
    return 0;
}

When I execute the program, it gives me the following output:

answer =1977800241 ,and size is=4

EDIT: But when I execute power(5,2), it gives a perfect result of 25.

Tlacenka
  • 520
  • 9
  • 15

1 Answers1

0

It is having integer overflow. You have to use unsigned long long or long long .

#include <stdio.h>
#include <stdlib.h>

typedef long long ll;
ll power(ll a,ll b){

ll c,i;
c=1;

for(i=1;i<=b;++i){
    c=c*a;
}
return c;
}

int main(){

ll nice=power(5,20);
printf("answer =%lld , and size is=%lld ", nice, sizeof(nice));
return 0;
}

NOTE:

You will have a good idea about this -> read this SO question.

QUESTION-2: WHat happens for a=5 b=100

Then you have to write your custom function for manipulating the multiplications. Use int arr[100] to hold the digits of the large number and then multiply it accordingly.C/C++ doesn't provide anything like BIgInt of Java, you have to build it.

Community
  • 1
  • 1
user2736738
  • 30,591
  • 5
  • 42
  • 56
  • Thanks that worked. But i have a question . The compiler is throwing a warning saying ""unknown conversion type character 'l' in format. "" But it still works. Also what about more bigger numbers? like base=100 & exponent = 20? – ashishkarn Sep 05 '15 at 18:57
  • @coderredoc Why do you `typedef` the `long long int` datatype? – splotz90 Sep 05 '15 at 18:59
  • splotz90.: I actually use this alot in competitive programming..habit I will say – user2736738 Sep 05 '15 at 19:00