题目链接:http://acdream.info/problem?pid=1115
题目定义了“完美的数”,初始的完美的数是1,3;对于任意完美的数 a,b 有2+a*b+2*a+2*b也是完美的数
例如 a=1 ,b=1 ; 2+1*1+2*1+2*1=7 7也是完美的数;
每组样例输入一个数,判断其是否为完美的数;
数据范围 1-1e9;
Math is very important, for those who are also in school, make sure you will learn more about math.
Salmon and Cat are good friends.Today Salmon ask Cat to help her judge whether a number is perfect or not. Perfect number is a kind of number defined by like this.
First, 1 and 3 are perfect number.Then if a and b are perfect numbers, 2+ab+2a+2b is also a perfect number.For example, 1 and 1 are perfect numbers, so 2+1+2+2 = 7 is perfect number.
If Cat can‘t help Salmon, Salmon will be sad and Cat will be much more sad. So Cat must solve the problem to maintain their friendship. Can you help Cat to solve the problem?
This problem contains multiple test cases.
Each test case contains one line.
Each line contains an interger n, 1 ≤ n ≤ 109.
For each test case, if n is a perfect number, output “Yes”, otherwise output “No”.
3 7 8
Yes Yes No
小伙伴想出的方法,也就是标准答案:
对于任意的完美数C
c+2 =2+a*b+2*a+2*b+2=(a+2)*(b+2); (公式啊~~看到数据跟这个式子就该想着推公式啊)
又因为初始的完美数 是 1,3;
所以任意完美数(C+2)都将是(1+2)3的倍数或者(3+2)5的倍数;
于是有了这个ac代码:
#include <stdio.h> int main(){ int n; while(scanf("%d",&n)!=EOF){ n += 2; while(n%5==0) n/=5; while(n%3==0) n/=3; if(n == 1) printf("Yes\n"); else printf("No\n"); } return 0; }
#include <stdio.h> #include <vector> #include <queue> #include <set> #include <algorithm> using namespace std; typedef long long ll; priority_queue<ll, vector<ll> ,greater<ll > >pq;//构造优先队列,使最小的优先弹出 ll num[300]; ll num2[300]; set <ll> se;//set记录数据,使得重复的数不入队; int binsearch(int n)//二分查找 { int head=0,tail=136; while(head<=tail) { if(num2[head]==n) return 1; if(num2[tail]==n) return 1; else { int mid=(head+tail)/2; if(num2[mid]==n) return 1; else if(num2[mid]>n) { tail=mid-1; } else { head=mid+1; } } } return 0; } int main() { se.insert(1); se.insert(3); num[1]=1;num[2]=3; pq.push(7); for(int i=3;;i++) { ll a=pq.top(); if(a>1e9)break;//如果由最小值求出的完美数超过范围,break; pq.pop(); if(a!=num[i-1])//不同的数的组合,可能求出相同的完美数,判断一下 num[i]=a; else i--; for(int j=1;j<=i;j++) { ll ans=2+a*num[j]+2*a+2*num[j]; if(se.count(ans))//set应用 continue; if(ans>1e10) break; pq.push(ans); se.insert(ans); } } priority_queue<ll, vector<ll> ,greater<ll > >pq2; pq2.push(3); for(int i=115;;i++)//之前打印了上面队列求出的数组num,i在115停止了 { ll a=pq2.top(); if(a>1e9) break; pq2.pop(); if(a!=num[i-1]) num[i]=a; else i--; for(int j=1;j<=i;j++) { ll ans=2+a*num[j]+2*a+2*num[j]; if(se.count(ans)) continue; if(ans>1e10) break; pq2.push(ans); se.insert(ans); } } sort(num,num+240);//排序 int k=0; for(int i=1;i<300;i++) { if(num[i]!=0&&num[i]!=num[i-1])//将num中 重复数字和0去掉 num2[k++]=num[i]; } int n; while(scanf("%d",&n)!=EOF) { int sign; sign=binsearch(n);//二分查找 if(sign) printf("Yes\n"); else printf("No\n"); } return 0; }
所以条条大路通罗马啊~
原文地址:http://blog.csdn.net/chaiwenjun000/article/details/45541589