求反阶乘的两种算法

Inverse Factorial反阶乘

3! = 1 * 2 * 3 = 6
4! = 3! * 4 = 24

f(0)=-1
f(1)=1
f(2)=2
f(6)=3
f(24)=4
f(7)=-1

算法1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public int inverseFactorial(int number) {
if (number == 1) {
return 1;
}
if (number < 1) {
return -1;
}
int i = 2;
int s = 1;
while (s < number) {
s = s * i;
i++;
}
if (s == number) {
return i - 1;
} else {
return -1;
}
}

算法2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public int inverseFactorial(int number) {
if (number == 1) {
return 1;
}
if (number < 1) {
return -1;
}
int i = 2;
while (number > 1) {
if (number % i != 0) {
return -1;
}
number /= i;
i++;
}
return i - 1;
}