UVa 10591 - Happy Number

来源:互联网 发布:java switch case例句 编辑:程序博客网 时间:2024/06/02 20:37

题目:求一个数每个数位上数字的平方和,为最后是否能转换化1。

分析:简单题、数论。求循环节。因为9^9*9 < 1000所以数据的转化集合是(1,1000),直接暴力模拟即可。

#include <stdio.h>#include <stdlib.h>#include <string.h>int used[ 1000 ];int bitsv( int v ){int sum = 0;while ( v ) {sum += (v%10)*(v%10);v /= 10;}return sum;}int happy( int v ){memset( used, 0, sizeof(used) );v = bitsv(v);while ( v != 1 && !used[v] ) {used[v] = 1;v = bitsv(v);}if ( v == 1 )return 1;return 0;}int main(){int N,T;while ( scanf("%d",&T) != EOF ) for ( int t = 1 ; t <= T ; ++ t ){scanf("%d",&N);if ( happy(N) )printf("Case #%d: %d is a Happy number.\n",t,N);elseprintf("Case #%d: %d is an Unhappy number.\n",t,N);}return 0;}

原创粉丝点击