南邮 OJ 1458 Happy Prime Number

Happy Prime Number

时间限制(普通/Java) :  1000 MS/ 3000 MS          运行内存限制 : 65536 KByte
总提交 : 132            测试通过 : 47 

比赛描述

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 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+0+0=49 1+3+0=10

is not a happy number
22=4
3
+7=58
1
+4+52=42
4
= 16 ... and never terminates

4+9=97 1+0=1

9+7=130

12+62=37 8+9=14 2+0=4

4=16
5
+8=89 4+2=20

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, ...

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 ≤ ≤ 1000000) 




输入

A positive number 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);
		}
	}
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值