欧拉计划35题

/**
* Circular primes
* Problem 35
*
* The number, 197, is called a circular prime
* because all rotations of the digits: 197, 971, and 719,
* are themselves prime.
*
* There are thirteen such primes below 100:
* 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, 97.
*
* How many circular primes are there below one million?
*
* @author dcb
*
*/

找出1000000以下所有的循环质数

分析,由于所有的循环项都必须是质数,因此,两位以上的数字中不应该有2,4,6,8,0,当他们在最后一位的时候必然是合数。
同理两位数以上的数字中也不应该包含5,当5是最后一位的时候,该数必然能够被5整除。

因此最终的质数由1,3,7,9构成

使用6层循环,判断组成的数字及其循环项是否都是质数,不考虑判断质数的时间复杂度的情况下,共需要进行4*4*4*4*4*4=4096次


String[] num = {"", "1", "3", "7", "9"};
int result = 4;
for (int i = 0; i < 5; i++){
for (int j = (i == 0) ? 0 : 1; j < 5; j++){
for (int k = (j == 0) ? 0 : 1; k < 5; k++){
for (int l = (k == 0) ? 0 : 1; l < 5; l++){
for (int m = 1; m < 5; m++){
for (int n = 1; n < 5; n++){
int a1 = new Integer(num[i] + num[j] + num[k] + num[l] + num[m] + num[n]);
int a2 = new Integer(num[j] + num[k] + num[l] + num[m] + num[n] + num[i]);
int a3 = new Integer(num[k] + num[l] + num[m] + num[n] + num[i] + num[j]);
int a4 = new Integer(num[l] + num[m] + num[n] + num[i] + num[j] + num[k]);
int a5 = new Integer(num[m] + num[n] + num[i] + num[j] + num[k] + num[l]);
int a6 = new Integer(num[n] + num[i] + num[j] + num[k] + num[l] + num[m]);
if (Utils.isPrime(a1)
&& Utils.isPrime(a2)
&& Utils.isPrime(a3)
&& Utils.isPrime(a4)
&& Utils.isPrime(a5)
&& Utils.isPrime(a6)) {
result++;
}


}
}
}
}
}
}

最后result为所求值


结果为:55



















猜你喜欢

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