编写一个算法来判断一个数是不是“Glodon number”。
一个“Glodon number”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为1,也可能是无限循环但始终变不到1,如果可以变成1,那么这个数就是Glodon Number。
示例:
输入:32
输出:true
解释:
3^2+2^2 = 13
1^2+3^2 = 10
1^2+0^2 = 1
注意:程序死循环问题
如何判断程序是否会死循环思路:将输入数与计算结果存进数组(结果集),每次的结果都在结果集进行判定如果再次出现说明程序进入死循环。
不考虑输入数判定
#include <iostream>
#include <vector>
#include <map>
#include <math.h>
using namespace std;
int sum(int k){
int s=0;
while(k){
s = s+pow(k%10,2);
k=k/10;
}
return s;
}
bool find(vector<int> &array,int a)
{
int size = array.size();
for(int i=0;i<size;i++)
if(array[i]==a)
return true;
return false;
}
int test_a()
{
int a;
cin>>a;
vector<int> array;
while(a!=1)
{
if(find(array,a))
{
cout<< "false"<<endl;
return 0;
}
else
{
array.push_back(a);
}
a=sum(a);
}
cout<<"true";
}
int test_b()
{
int a;
cin>>a;
map<int,int> mymap;
while(a!=1)
{
if(mymap.count(a) > 0)
{
cout<< "false"<<endl;
return 0;
}
else
{
mymap[a] = 1;
}
a=sum(a);
}
cout<<"true";
}
int main()
{
//test_b();
test_a();
return 0;
}