Happy Prime Number
总提交 : 132 测试通过 : 47
比赛描述
A Happy Number can be defined as follows. From a positive integer n, calculate the sum of square of each digit of n. Then from that sum, repeat the same process over and over again. This cycle terminates if and only if there is 1 in the sequence. Hence, we call the number n a happy number if it generates a finite sequence. Otherwise, the endless cycle occurs (1 never appears in the sequence). We
may call the number generating an endless cycle an unhappy number . Observe the following examples:
700 is a happy number72+02 +02 =49 12 +32 +02 =10
2 is not a happy number
22=4
32 +72 =58
12 +42 +52=42
42 = 16 ... and never terminates
42 +92 =97 12 +02 =1
92 +72 =130
12+62=37 82 +92 =14 22 +02 =4
42 =16
52 +82 =89 42 +22 =20
A Prime Number is an integer greater than 1 that can be divided only by 1 and itself. Here are some prime numbers: 2, 3, 5, 7, 11, 13, 17, 19, ...
A Happy Prime Number is a prime number which also satisfies the happy number condition such as 7, 13, 19, ...
Your task is to write a program to show all happy prime numbers less than or equal to a given numbern. (10 ≤ n ≤ 1000000)
输入
A positive number n is the only input of the program
输出
the program prints all happy numbers in ascending order, one number in a line.
样例输入
20
样例输出
7
13
19
提示
用于 NUPT ACM 2010 Personal Ranking Contest 5
题目来源
The 1st ACM-ICPC Thailand National Programming Contest 2009
#include<iostream>
#include<set>
using namespace std;
bool isPrime[1000001];
char isHappy[1000001]; //1确定happy,0不知道,-1确定不是happy
bool happy(int n){
if(1==isHappy[n]){
return 1;
}else if(-1==isHappy[n]){
return 0;
}
set<int> iSet;
set<int>::iterator it;
iSet.insert(n);
int digit,sum;
int temp = n;
while(1){
sum = 0;
while(temp){
digit = temp%10;
sum += digit*digit;
temp /= 10;
}
if(1==sum || 1==isHappy[sum]){ //确定是happy数
isHappy[n] = 1;
break;
}
if(-1==isHappy[sum] || iSet.count(sum)){ //确定不是happy数
isHappy[n] = -1;
break;
}
iSet.insert(sum);
temp = sum;
}
if(1==isHappy[n]){
for(it=iSet.begin(); it!=iSet.end(); ++it){
isHappy[*it] = 1;
}
return 1;
}
for(it=iSet.begin(); it!=iSet.end(); ++it){
isHappy[*it] = -1;
}
return 0;
}
int main(){
int i,j,n;
scanf("%d",&n);
isPrime[0]=isPrime[1]=0;
isPrime[2]=1;
for(i=3; i<=n; i++){ //大于2的偶数都不是素数
isPrime[i] = 1;
}
for(i=4; i<=n; i+=2){ //大于2的偶数都不是素数
isPrime[i] = 0;
}
for(i=3; i<<1<=n; i+=2){
if(isPrime[i]){
for(j=(i)<<1; j<=n; j+=i){
isPrime[j] = 0;
}
}
}
for(i=2; i<=n; i++){
if(isPrime[i] && 1==happy(i)){
printf("%d\n",i);
}
}
}