Reputation:
I need to write a program that a user inputs a long positive number m. I need to find out what is the smallest int number n such that n! > m.
So far I have written such a code:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
long number = scanner.nextLong();
int fact = 1;
int count =1;
while (fact <= number) {
count ++;
fact *=count;
}
System.out.println(count);
}
}
Test input: 6188989133 Correct output: 13
Your code output:
My code output is empty. What I am missing here?
Upvotes: 0
Views: 767
Reputation: 4285
fact
should be declared as long
. Check the code below:
public class TestJava {
public static void main(String[] args) {
try{
System.out.println("Input number: ");
Scanner scanner = new Scanner (System.in);
long number = scanner.nextLong();
if(number >= 2432902008176640000L) {
// log an appropriate message like can not handle
// long value greater than 2432902008176640000L
return 21;
}
long fact = 1;
int count =1;
while (fact <= number) {
count ++;
fact *=count;
}
System.out.println("output: "+ count);
}catch(Exception e){
e.printStackTrace();
}
}
}
Update (Warning):
As @Pshemo mentioned, with out the if condition
, the above code is fine till 20!, but after that it will cause the infinite loop problem. Hence this condition has to be taken care of. Code has been updated accordingly.
Upvotes: 0
Reputation: 19555
You have to use long
for the fact
variable. When you use int
the possible values are between -2,147,483,648
and 2,147,483,647
.
However, you will never exceed the input number 6,188,989,133
, so your while(fact <= number)
loop will never exits. Every integer value possible will be smaller than 6,188,989,133
. This explains why your code output is "empty", as it doesn't reach that System.out.println(count);
line at all.
Keep in mind that the long
type has such a limit as well, values can only be between -9,223,372,036,854,775,808
and 9,223,372,036,854,775,807
. When the input number is that big, you will not find the correct fact
value which will be greater than the input because you are limited by the long
type value range. As an example, for the input number 9,000,000,000,000,000,000
(which is inside the long
type value range) the next factorial number is 51,090,942,171,709,440,000
(the value of 21!
), which is outside the long
type value range.
You can use the java.math.BigInteger
class which has an "unlimited" range of possible values and do your math operations on BigInteger
objects.
Upvotes: 6