0

Most inputs to the program work fine but when i use large numbers e.g. 20 the value is incorrect. Is there a way I could convert the decimal numbers and output them as binary? Thank you.

int n = Comp122.getInt("What number would you like to make a factorial?");
int factorial = 1;
for (int i = 1 ; i<=n ; i++) {
    factorial*=i;
    System.out.println(factorial);
}
Gray
  • 115,027
  • 24
  • 293
  • 354
  • 3
    The factorial of 20 is 2432902008176640000, which is larger than the max value of an int. How you later display that int (whether as decimal, binary or base 42) won't change the fact that an int cannot be used to save a number that big. If you work with number that large that can easily get bigger than an Integer or Long max value, using a class without a maximum value like `BigInteger` instead of primitive data types is what you'll have to do, – OH GOD SPIDERS Feb 24 '21 at 16:00
  • Probably [this post](https://stackoverflow.com/questions/5372279/how-can-i-convert-very-large-decimal-numbers-to-binary-in-java) can help You. – Kaplan Feb 24 '21 at 16:07

3 Answers3

2

You’re encountering integer overflow at 13!, which exceeds the largest number that an int can hold, which is 231 (about 2.1 x 109).

You can change the type of your variable from int to long, which can hold 263 (about 1.9 x 1019), but that too will exceed its limit at 20!

To handle arbitrarily large numbers, use the BigInteger class as your variable type. Your code would then something like:

BigInteger factorial = BigInteger.ONE;
for (int i = 2; i < n; i++) {
    factorial = factorial.multiply(néw BigInteger(i + ""));
}

By the way, to output an integer as binary or hex:

System.out.println(Integer.toBinaryString(n));
System.out.println(Integer.toHexString(n));
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

n! becomes very big and probably Integer cannot hold it as Integer has a limitation of 2,147,483,647.

That's not the problem of output, but rather you hit an overflow. If you have a infinite range of input that could potentially fit in a BigInteger, you could try BigInteger. Otherwise, probably you'd like to use some unlimited data structure such as String. And do the calculation digit by digit.

Something like: https://www.geeksforgeeks.org/multiply-large-numbers-represented-as-strings/

Noah Han
  • 141
  • 1
  • 6
0

20 the value is incorrect?

value of 20! = 2,432,902,008,176,640,000.

In java, an integer can properly handle any positive value less than 2,147,483,648.

int | 4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647

So, using int you can not handle this type of big value.

long datatype can be used for factorials only for n <= 20.

For larger values of n, we can use the BigInteger class from the java.math package, which can hold values up to 2^Integer.MAX_VALUE:

Md Kawser Habib
  • 1,966
  • 2
  • 10
  • 25