AOJ 759.会绕圈的数

会绕圈的数
Time Limit: 1000 ms   Case Time Limit: 1000 ms   Memory Limit: 64 MB
Total Submission: 44   Submission Accepted: 5
 
Description
任意一个正整数,把它的每一位数字都平方后相加得到一个数;将这个数的每一位数字再平方相加;依次进行就会产生循环现象。
例如:1234。
1ˆ2+2ˆ2+3ˆ2+4ˆ2=1+4+9+16=30
3ˆ2+0ˆ2=9
9ˆ2=81
8ˆ2+1ˆ2=64+1=65
6ˆ2+5ˆ2=36+25=61
6ˆ2+1ˆ2=36+1=37
3ˆ2+7ˆ2=9+49=58
5ˆ2+8ˆ2=25+64=89
8ˆ2+9ˆ2=64+81=145
1ˆ2+4ˆ2+5ˆ2=1+16+25=42
4ˆ2+2ˆ2=16+4=20
2ˆ2+0ˆ2=4+0=4
4ˆ2=16
1ˆ2+6ˆ2=1+36=37
由于前面已出现过37,这时就产生了循环。
设计一个程序,对给定的一个数,打印出到出现循环为止的所有数。

 

Input
输入包括多组测试数据,每组测试数据占一行并且只有一个正整数m(m<10000000),当m=0时表示输入结束。

 

Output
对每组测试数据输出一行结果,结果中包括到第一次产生循环时的所有整数。

 

Sample Input
Original Transformed
1234 
67834807
0

 

Sample Output
Original Transformed
1234   30   9   81   65   61   37   58   89   145   42   20   4   16   37   
67834807   287   117   51   26   40   16   37   58   89   145   42   20   4   16   

 

 

用一个函数来模拟操作即可

要注意的是输出格式

题目中每个数字后面都是三个空格

 

AC代码:GitHub

 1 /*
 2 By:OhYee
 3 Github:OhYee
 4 HomePage:http://www.oyohyee.com
 5 Email:oyohyee@oyohyee.com
 6 Blog:http://www.cnblogs.com/ohyee/
 7   
 8 かしこいかわいい?
 9 エリーチカ!
10 要写出来Хорошо的代码哦~
11 */
12   
13 #include <cstdio>
14 #include <algorithm>
15 #include <cstring>
16 #include <cmath>
17 #include <string>
18 #include <iostream>
19 #include <vector>
20 #include <list>
21 #include <queue>
22 #include <stack>
23 #include <map>
24 using namespace std;
25   
26 //DEBUG MODE
27 #define debug 0
28   
29 //循环
30 #define REP(n) for(int o=0;o<n;o++)
31   
32 const int maxn = 1005;
33 bool visited[maxn];
34   
35 inline int sq(int n) {
36     int ans = 0;
37     while(n) {
38         ans += (n % 10)*(n % 10);
39         n /= 10;
40     }
41     return ans;
42 }
43   
44 bool Do() {
45     int n;
46     if(scanf("%d",&n),n == 0)
47         return false;
48   
49     memset(visited,false,sizeof(visited));
50     int k = n;
51     while(k>maxn||!visited[k]) {
52         if(k < maxn)
53             visited[k] = true;
54         printf("%d   ",k);
55         k = sq(k);
56     }
57     printf("%d   \n",k);
58     return true;
59 }
60   
61 int main() {
62     while(Do());
63     return 0;
64 }

 

posted @ 2016-05-15 23:29  OhYee  阅读(162)  评论(0编辑  收藏  举报