0

I want to write a program that calculates expontiation using the Gauss' algorithm but if give input etc base=2,exp=50 i get as a result 0.0000.

#include<stdio.h>

float fastpower(int a,int b);
main()
{     
      int base,exp;
      printf("Base:\n");
      scanf("%d",&base);
      printf("Exp:\n");
      scanf("%d",&exp);
      fastpower(base,exp);
      system("pause");
}
float fastpower(int a,int b)
{               
      double result=1;
      while (b>0) 
      {    
            if (b%2!=0) 
            result=result*a;                       
            b=(b/2);
            a=a*a;
      }
      printf("result is  %lf\n",result);
}
harper
  • 13,345
  • 8
  • 56
  • 105

1 Answers1

2

Declare a as long (int64):

/* 
   compute a**b
*/
/* double fastpower(double a, int b) is even more better */
double fastpower(long a, int b) { /* double is more natural here: double result */    
  double result = 1.0;

  while (b > 0) {    
    if (b % 2 != 0) 
      result *= a;                       

    b /= 2;
    a *= a; /* <- a is long to prevent overflow here */
  }

  /* You'd rather not output in functions */
  printf("result is  %lf\n", result);

  return result; /* do not forget to return the result*/  
}

But long could do overflow as well (e.g. 10**50); in this case use double for a

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 1
    Will it work equally good for [5^50](https://www.google.co.in/search?q=5%5E50&oq=5%5E50&aqs=chrome..69i57j69i60l3j0l2.2191j0j7&sourceid=chrome&es_sm=93&ie=UTF-8)? – Mohit Jain May 20 '14 at 12:05
  • 1
    long is a 32-bit type on Windows or any systems that use LLP64 model – phuclv May 21 '14 at 06:07