Search code examples
javainteger-overflow

Write a function that prints out every digit of n^100


I was asked to write a Java function that takes an integer, n, and prints out the value n^100.

I have no idea how to approach this. I know by conventional means it would overflow as n grows. Answers such as: 5.32 x 10^20 are not acceptable. It must be every digit.

So, for example:

public void byHundred(int n) {
  result = //some computation that yields the string
  System.out.println(result);
}

So, byHundred(23) prints out "14886191506363039393791556586559754231987119653801368686576988209222433278539331352152390143277346804233476592179447310859520222529876001"


Solution

  • You could use BigInteger and something like,

    public static void byHundred(int n) {
        BigInteger bi = BigInteger.valueOf(n);
        String result = bi.pow(100).toString();
        System.out.println(result);
    }
    
    public static void main(String[] args) {
        byHundred(23);
    }
    

    Output is 14886191506363039393791556586559754231987119653801368686576988209222433278539331352152390143277346804233476592179447310859520222529876001 (as requested).