Internet
Internet

Reputation: 15

Power of Power to calculate in Java

I have a program to write. The requirement is 1. Implement code (choose your favorite language) which will calculate the value of 2^(3^(4^(5^6)))

What I have written is this so far ( for 4^(5^6).However, I get 0 as output despite the fact I have even changed the second argument from integer to long.A little help is needed.Here is my code:

public static void main(String args[]) {
    int i=4,j=5,k=6;
    System.out.println(pow(i,pow(j,k)));
}

public static long pow(int c, long l){       
    long n=1;
    for(int i=0;i<l;i++){
        n=c*n;
    }
    return n;            
}

Upvotes: 0

Views: 403

Answers (7)

Amir Pashazadeh
Amir Pashazadeh

Reputation: 7282

You can use Java's BigInteger, but I'm not sure whether such a huge number can be stored in memory.

Upvotes: 1

Leo
Leo

Reputation: 1919

did you try this algorithm ? Exponentation by squaring

Upvotes: 0

quant
quant

Reputation: 2224

First of all, you might use Math.pow(2, 3), to calculate 2 ^ 3. However since the output is that large, as shown in the following code, even double will return Infinity:

package test;

public class Test {

    public static void main(String[] args) throws Exception {
        // 2^(3^(4^(5^6)))
        System.out.println(Math.pow(2, Math.pow(3, Math.pow(4, Math.pow(5, 6)))));
    }

}

However you might use java.math.BigDecimal, which can handle this large integers. For this question I would propose python, were you could just write

2 ** (3 ** (4 ** (5 ** 6)))

EDIT:

Do you know that 4 ** (5 ** 6) already is

http://paste.ubuntu.com/6840260/

do you really want to calculate with this number in Java, which is not the fastest language for math problems?

Upvotes: 1

Happy
Happy

Reputation: 1855

As you said you can choose the language. I advise you to implement this computation with Matlab or Octave:

2^3^4^5^6

prints the result you expect.

Upvotes: 2

0x5C91
0x5C91

Reputation: 3505

4^(5^6) equals 4^15625, which is approximately 1,53*10^9407, a number which greatly exceeds the maximum value for the Long type, which is (2^64)-1.

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Upvotes: 4

webuster
webuster

Reputation: 2510

These numbers are humongous. Really. 5^6 = 15625. Raise 4 to that power and you'll get enough digits as there are particles in the known Universe.

Your problem with 0 comes from the fact that 4 is 100 in binary. Multiply by 4 and you get 10000 in binary. Raise to a little more than that (max power 8, 16, maybe 32 if data types support it; talking in general) and you'll drop the single 1 bit you had out of the integer representation => 0.

Upvotes: 3

Amit Sharma
Amit Sharma

Reputation: 6154

The output is large enough and trips over to zero after crossing Long.MAX_VALUE.

Upvotes: 1

Related Questions