uva Happy Number

来源:互联网 发布:十月革命100周年 知乎 编辑:程序博客网 时间:2024/05/29 17:29
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>


using namespace std;
#define mod 10007


struct node
{
    int num;
    int next;
};


node hashnode[mod];
int head[100000], cnt;


void init()
{
    memset(head, -1, sizeof(head));
    cnt = 0;
}


int gethash( int n)
{
    return (n & 0x1f1f1f) % mod;
}


int inserthash( int n)
{
    int h = gethash(n);
    hashnode[cnt].num = n;
    hashnode[cnt].next = head[h];
    head[h] = cnt++;
}


long long fan(int n)
{
    long long res = 0;
    int temp;
    while(n)
    {
        temp = n%10;
        res += temp*temp;
        n /= 10;
    }
    return res;
}


int findhash( int n )
{


    int h = gethash(n);
    for( int i = head[h]; i != -1; i = hashnode[i].next)
    {
        if(hashnode[i].num == n )
            return n;
    }
    inserthash(n);
    long long res = fan(n);
    findhash(res);


}






int main()
{
    int n;
    int cases = 1;
    inserthash(1);
     int t;
     scanf("%d",&t);
    while( t-- )
    {
        scanf("%d",&n);
        init();
        int res = n;
        printf("Case #%d: ",cases++);
        int ans = findhash(res);
        if(ans == 1)
            printf("%d is a Happy number.\n",n);
        else
            printf("%d is an Unhappy number.\n",n);
    }
    return 0;
}
0 0