Raising Powers (Example Code)

Jim Wright jimwright at yosemiteconsultants.com
Thu Dec 4 03:53:14 CET 2003

I had a difficult time understand GMP powers and found the manual to be of
no help. I finally figured them out

And have decided to post my code if anyone would like to look at it. Hope
you find it useful. The reason I am

Using GMP for powers is because of C's integer, double, etc limitations.


/* Program to raise powers using gmp library

   Option to write to file and option to write to screen    

   Written by Daniel Amaya - 12/04/03 */


/* Include Files */


#include <stdio.h>

#include <stdlib.h>

#include <math.h>

#include <gmp.h>


/* File Pointer */

FILE *fptr;


/* Clears Screen, Duh */

void ClearScreen(void)


      int cls = 0;


      while (cls < 25)

      { printf("\n");

            cls++; }






      mpz_t result, base; // Sets these as GMP Integers

      unsigned long int exponent; // Set exponent as an unsigned long

      char answer; 

      fptr = fopen("output2.txt", "w+"); // Sets fptr to File output2.txt
with write capability


      /* Initializes base and result */




      /* Asks user for base and puts input into GMP Integer base */

      gmp_printf("Please Enter a Base \n");

      gmp_scanf("%Zd", base);


      /* Asks user for exponent and puts input into unsigned long int
exponent */

      gmp_printf("Please Enter a Exponent \n");

      gmp_scanf("%ld", &exponent);


      /* GMPS Power function, raises base ^ exponent and puts the answer
into GMP integer result */

      mpz_pow_ui(result, base, exponent);


      /* Asks user if they want output to screen or file. Getchar gets the
input and than assigns it into variable answer */

      printf("Would you like this outputted to a file? Y/N\n");


      answer = getchar();


      /* uses gmp file print function and outputs to output2.txt if user
entered Y/y. If user enters N/n uses gmp printf function and outputs to
screen */

      if ((answer == 'Y') || (answer == 'y'))

            { gmp_fprintf(fptr, "%Zd\n", result); }

      if ((answer == 'N') || (answer == 'n')) {


            gmp_printf("%Zd\n", result); }            


      /* Clears base and result */





      /* If you don't get this.. STOP PROGRAMMING NOW */

      return 0; }


-------------- next part --------------
An HTML attachment was scrubbed...
URL: /list-archives/gmp-discuss/attachments/20031204/a0897480/attachment.htm

More information about the gmp-discuss mailing list