Skip to content

Instantly share code, notes, and snippets.

@mkrupczak3
Last active October 5, 2022 18:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkrupczak3/5df15400873ffba9c50bed6a1087e71b to your computer and use it in GitHub Desktop.
Save mkrupczak3/5df15400873ffba9c50bed6a1087e71b to your computer and use it in GitHub Desktop.
A recursive exponent cacluation calculator for integers, sped up by memo-ization
import java.util.Scanner;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Dictionary;
import java.util.Hashtable;
class Main {
public static void main(String args[]){
Scanner beepBoop = new Scanner(System.in);
int base = -1;
while(base <= -1) {
System.out.println("Please enter an integer for the base below the exponent:");
while(true) {
try {
base = beepBoop.nextInt();
if (base < 0) {
System.out.println("ERROR: please enter a natural number >= 0");
continue;
}
break;
} catch (InputMismatchException e) {
System.out.println("ERROR: your response was not a natural number. Try again.");
beepBoop.next();
continue;
}
}
}
int exponent = -1;
while(exponent <= -1) {
System.out.println("Please enter an integer for the exponent:");
while(true) {
try {
exponent = beepBoop.nextInt();
if (exponent < 0) {
System.out.println("ERROR: please enter a natural number >= 0");
continue;
}
break;
} catch (InputMismatchException e) {
System.out.println("ERROR: your response was not a natural number. Try again.");
beepBoop.next();
continue;
}
}
}
Raiser mahBoy = new Raiser();
long result = mahBoy.calculate_power(base, exponent);
System.out.println("Result is: " + Long.toString(result));
}
}
class Raiser {
private Dictionary memo_table;
Raiser() {
this.memo_table = new Hashtable();
}
public long calculate_power(int x, int y) {
if (y == 1) {
return x;
}
if (y == 0) {
return 1;
}
if (x == 0) {
return 0;
}
if (x == 1) {
return 1;
}
Long iterValue = null;
Long cached = null;
int[] tuple = {x, y/2};
cached = (Long) memo_table.get(tuple);
if (y % 2 == 0) {
if (cached != null) {
iterValue = cached;
} else {
iterValue = calculate_power(x, y/2);
iterValue = iterValue * iterValue;
}
int[] pair = {x, y};
memo_table.put(pair, iterValue);
return iterValue;
} else {
if (cached != null) {
iterValue = cached;
} else {
iterValue = calculate_power(x, y/2);
}
iterValue = iterValue * iterValue * x;
int [] pair = {x, y};
memo_table.put(pair, iterValue);
return iterValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment