Reputation: 1
I would like to find the smallest factorial of a given long number. For example, if you enter the number 100, the code should give the factorial 5, since 5! = 1 * 2 * 3 * 4 * 5 = 120 is closer than the factorial 4! = 1 * 2 * 3 * 4 = 24. I have written the code below, but when I enter 100, I only get the factorial 3.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long number = scanner.nextLong();
long factorial = 1;
long sum;
do {
sum = number / factorial;
factorial++;
} while (number <= sum);
System.out.println(factorial);
}
}
What am I doing wrong here?
Upvotes: 0
Views: 639
Reputation: 40034
Here is one way. This will return the smallest factorial greater than the number. A record is used to return the information.
record Factorial(long n, long nFact) {}
Integer[] data = {1,2,5,10,200,500,2520,1000, 5040, 720, 2000, 3000, 10_000};
for (long i : data) {
Factorial result = smallestFactorial(i);
System.out.printf("For %-8d the smallest >= %8d is (%d! = %d)%n",
i, i, result.n, result.nFact);
}
prints
For 1 the smallest >= 1 is (2! = 2)
For 2 the smallest >= 2 is (2! = 2)
For 5 the smallest >= 5 is (3! = 6)
For 10 the smallest >= 10 is (4! = 24)
For 200 the smallest >= 200 is (6! = 720)
For 500 the smallest >= 500 is (6! = 720)
For 2520 the smallest >= 2520 is (7! = 5040)
For 1000 the smallest >= 1000 is (7! = 5040)
For 5040 the smallest >= 5040 is (7! = 5040)
For 720 the smallest >= 720 is (6! = 720)
For 2000 the smallest >= 2000 is (7! = 5040)
For 3000 the smallest >= 3000 is (7! = 5040)
For 10000 the smallest >= 10000 is (8! = 40320)
This method calculates the factorial while comparing to the passed argument.
public static Factorial smallestFactorial(long n) {
if (n <= 1) {
return new Factorial(2,2);
}
long fact = factorials.floorKey(n);
int k = factorials.get(fact);
while (n > fact) {
fact*=++k;
factorials.putIfAbsent(fact, k);
}
return new Factorial(k, fact);
}
The output formatting is incidental and can of course be changed to suit your requirements.
Upvotes: 1
Reputation: 31
you should calculate the factorial of numbers, untill you find an equal or smaller number than the number you entered, as shown in the following code :
import java.util.Scanner;
class Main {
public Long factorial (int n){
long p = 1L;
for(int i = 1; i<= n ; i++){
p=p*i;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long number = scanner.nextLong();
long i = 1;
while (factorial(i) < number) {
i++;
}
System.out.println(i);
}
Upvotes: 2