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?
CodePudding user response:
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);
}
CodePudding user response:
Here is one way. This will return the factorial closest to the number. If there is a tie, the lowest factorial will be returned.
int[] data = {0,1,2,5,10,200,500,2520,1000,2520, 2000, 3000, 10_000};
for (int d :data) {
System.out.println(d ": closest factorial = " closestFactorial(d));
}
prints
0: closest factorial = 1!
1: closest factorial = 1!
2: closest factorial = 1!
5: closest factorial = 3!
10: closest factorial = 3!
100: closest factorial = 5!
200: closest factorial = 5!
500: closest factorial = 6!
2520: closest factorial = 6!
1000: closest factorial = 6!
2520: closest factorial = 6!
2000: closest factorial = 6!
3000: closest factorial = 7!
10000: closest factorial = 7!
This method calculates the factorial while comparing to the passed argument.
- continue calculating factorials until the factorial exceeds the argument.
- compare the
factorial - argument
to theargument - previous factorial
. Return the proper factorial based on the comparison.
public static int closestFactorial(long n) {
if (n <= 2) {
return 1;
}
long fact = 2;
int k = 2;
while (n > fact) {
fact*= k;
}
long previousFact = fact/k;
return fact - n < n - previousFact ? k : k-1;
}
If you want to see the actual factorial you can replace the last statement with.
return fact - n < n - previousFact ? fact : previousFact;