Saturday 15 August 2015

C - Powers of a^b for big numbers using Array -



C - Powers of a^b for big numbers using Array -

the question consists of 2 numbers, , b, , reply sum of digits of a^b.

i have written below code. giving right result in cases. when input such < b, after giving right answer, getting segmentation fault.

i tried lot debug not identify issue. help appreciated.

thanks in advance..!

#include<stdio.h> void powerfulness (int, int, int *product); int main() { int a,b,product[200]; scanf("%d %d",&a, &b); power(a,b,product); homecoming 0; } void power(int a, int b, int *product) { int i,m,j,x,temp,sum=0; int *p = product; *(p+0)=1; //initializes array 1 digit, digit 1 m=1; // initializes digit counter temp=0; //initializes carry variable 0. for(i=1;i<=b;i++) { for(j=0;j<m;j++) { x = (*(p+j))*a+temp; *(p+j)=x%10; temp = x/10; } while(temp>0) //while loop store carry value on array. { *(p+m)=temp%10; temp = temp/10; m++; } } //printing result for(i=m-1;i>=0;i--) sum = sum + *(p+i); printf("\n%d",sum); printf("\n"); }

i hope below code trying do. simple , looks too.

#include<stdio.h> void powerfulness (int, int); int main() { int a,b; scanf("%d %d",&a, &b); power(a,b); homecoming 0; } void power(int a, int b) { int c=1,sum=0; while(b>0) { c = c*a; b--; } printf("%d\n",c); while(c!=0) { sum = sum+(c%10); c =c/10; } printf("%d\n",sum); }

c

No comments:

Post a Comment