26

in python with a simple loop you can calculate, let's say 600! it's a very very big number but python can easily take care of it in a fraction of a second.even it's more than 200 digit long. in java in the other hand you are bound to 64bit literals (long data type). so the machine will return 0.
is there any way to overcome this?

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
Confuzzeled David
  • 363
  • 1
  • 5
  • 10

1 Answers1

51

You can use the Java BigInteger class.

And a simple example:

import java.math.BigInteger;

BigInteger k = BigInteger.valueOf(10000L);
k = k.pow(10000);
//k is now 10000^10000 
System.out.println(k.toString());

It's important to know that the class is immutable. You can also look into the similar BigDecimal class for arbitrary precision signed decimal numbers.

tbodt
  • 16,609
  • 6
  • 58
  • 83
Kon
  • 10,702
  • 6
  • 41
  • 58
  • you forget to mention import java.math.BigInteger; Wow!thanks i love java again! – Confuzzeled David Jul 30 '13 at 08:20
  • Added import statement – Kon Jul 30 '13 at 08:20
  • 3
    @Kon Nothing wrong but its better to link latest API documentation – exexzian Jul 30 '13 at 08:22
  • Because the class is not final a `BigInteger` instance is only immutable if it is not a subclass of `BigInteger`. – Joseph Earl Jul 30 '13 at 16:42
  • @Joseph: Is that true; can a subclass change the internal value of the `BigInteger`? If not, I'd say your statement is false - a subclass can add its own, mutable fields, but any method accessing an instance of that class through `BigInteger` can still treat the `BigInteger` as an immutable object. – BlueRaja - Danny Pflughoeft Jul 30 '13 at 17:01
  • @BlueRaja-DannyPflughoeft no it cannot, but a subclass could add some property that *was* mutable, or override the methods and return itself but with a different state -- in which case the subclass could not be said to be immutable. It is mostly a technical point -- for all intents and purposes you can probably assume anything that is an instance of BigInteger is immutable in your program. If you are designing your own library, then avoid the same mistake and make your immutable class final. See e.g. http://stackoverflow.com/questions/146311/immutable-class-should-be-final – Joseph Earl Jul 31 '13 at 00:46