快樂數
若將一個整數 n 的所有數字拆開分別平方後再相加,如此反覆進行至只剩個位數之後,其結果為 1 ,則我們稱 n 為快樂數。
例如
32 → 3 ^ 2 + 2 ^ 2 = 13
13 → 1 ^ 2 + 3 ^ 2 = 10
10 → 1 ^ 2 + 0 ^ 2 = 1
可以稱32為快樂數。
Input的第一個數字為測資個數;Output為Happy或Not Happy。
範例輸入:
2
32
87
範例輸出:
Happy
Not Happy
/*----- ----- ----- -----*/ //1-happy number //Made by 105502555 Teemo Hsu(Synasaivaltos) //Date: 2018/03/15 /*----- ----- ----- -----*/ #include <iostream> #include <vector> using namespace std; int square(int x) { return x*x; } int main(void) { int n; cin >> n; vector<bool> ans; while(--n>=0) { int a; cin >> a; while(a>9) { int sum=0; while(a!=0) { sum+=square(a%10); a/=10; } a=sum; } ans.push_back((a==1)?true:false); } for(int i=0;i<ans.size();cout<<((ans.at(i)==true)?"Happy\n":"Not Happy\n"),i++); return 0; } |