欧拉计划41题

/**
* Pandigital prime
* Problem 41
*
* We shall say that an n-digit number is pandigital
* if it makes use of all the digits 1 to n exactly once.
* For example, 2143 is a 4-digit pandigital and is also prime.
*
* What is the largest n-digit pandigital prime that exists?
*
*/
题目,求最大的由1-n构成的质数

分析:
定理:如果一个数各个位数上的和能被3整除,则该数能被3整除

首先我们需要判断n的位数
1,显然不行
n=2,能被3整除,没有质数
n=3,能被3整除,没有质数
n=4,可能存在满足条件的数
n=5,能被3整除,没有质数
n=6,能被3整除,没有质数
n=7,可能存在满足条件的数
n=8,能被3整除,没有质数
n=9,能被3整除,没有质数
因此,最大的数只可能由1-7构成,或者1-4构成
循环判断,找出最大的质数

代码实现:
for (int i = 7654321; i > 1000000; i--){
if (Utils.isPandigital(i + "", 7) && Utils.isPrime(i)){
return i;
}
}

for (int i = 4321; i > 1000; i--){
if (Utils.isPandigital(i + "", 4) && Utils.isPrime(i)){
return i;
}
}

判断是否质数和是否由1-n构成的方法在这不提供了

结果:7652413
























猜你喜欢

转载自535260620.iteye.com/blog/2285285