20-CS-122-001 Computer Science II Spring 2012
Power class

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev     Next     Lectures     power.cc     power.h     powertest.cc     stacker.cc     stacker.h     primes.cc

#include <stdio.h>
#include <math.h>
#include "bigint.h"
#include "power.h"

Power::Power () {  bitstack = new Stack(NULL);  }

BigInt *Power::pow (int x, int y, int m) {
   // Bits of the exponent go on a stack
   while (y > 1) {
      bitstack->push(new bool(y%2));
      y /= 2;
   }
   
   // Initialize p to the mantissa, m to the modulus
   BigInt *modulus = new BigInt(m);
   BigInt *mantissa, *p;
   p = mantissa = new BigInt(x);
   
   // Repeatedly square or square and multiply until 
   // all bits of y are considered
   while (!bitstack->empty()) {
      p = p->multiply(p);
      p = p->mod(modulus);
      if (*(bool*)bitstack->pop()) { 
         p = p->multiply(mantissa);
         p = p->mod(modulus);
      }
   }
   return p;
}

BigInt *Power::pow (int x, int y) {
   // Bits of the exponent go on a stack
   while (y > 1) {
      bitstack->push(new bool(y%2));
      y /= 2;
   }
   
   // Initialize p to the mantissa, m to the modulus
   BigInt *mantissa, *p;
   p = mantissa = new BigInt(x);
   
   // Repeatedly square or square and multiply until 
   // all bits of y are considered
   while (!bitstack->empty()) {
      p = p->multiply(p);
      if (*(bool*)bitstack->pop()) p = p->multiply(mantissa);
   }
   return p;
}