题目
Wilson primes满足以下条件。让我们用P代表一个质数。
然后((P-1)! + 1) / (P * P)可以算出一个整数。
您的任务是创建一个函数,如果给定的数字是Wilson prime返回true
,否则返回false
。
注:n!表示n的阶乘,即当n>0时n! = 1 * 2 * ···* (n-1) * n,当n=0时0! = 1.
测试用例:
import static org.junit.Assert.*;
import org.junit.Test;
public class WilsonPrimeTest {
@Test
public void test1() {
assertEquals(false, WilsonPrime.am_i_wilson(0));
}
@Test
public void test2() {
assertEquals(false, WilsonPrime.am_i_wilson(1));
}
@Test
public void test3() {
assertEquals(true, WilsonPrime.am_i_wilson(5));
}
}
解题
My
按照题目意思解,但是对于n为1不知道怎么就不是这类质数,也简单研究了威尔逊定理,还是没有想明白,我的代码对于1和563的测试用例是失败的。
public static boolean am_i_wilson(double n) {
return (factorial(n-1) + 1) % (n*n) == 0;
}
public static double factorial(double number) {
if (number <= 1) {
return 1;
} else {
return number * factorial(number - 1);
}
}
Other
注:现时所知的威尔逊质数只有5、13和563(OEIS:A007540),若还有其他这类质数,必然大于500000000。
public class WilsonPrime {
public static boolean am_i_wilson(double n) {
return n == 5 || n == 13 || n == 563;
}
}
后记
最后败在别人的投机取巧,自己都不知道错在哪里,真是的,已经困扰我几天了。
网友评论