编写一个算法来判断一个数是不是“Glodon number”。

编写一个算法来判断一个数是不是“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;

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值