返回列表 發帖

310 函式與陣列 (阿姆斯壯數)

1. 題目說明:
請依下列題意進行作答,使輸出值符合題意要求。

2. 設計說明:
請撰寫一程式,包含名為compute()的函式,接收主程式傳遞的一個整數n(0 < n < 1000),compute()輸出所有小於n的阿姆斯壯數並回傳總和至主程式輸出。

阿姆斯壯數的定義:若為k位數的正整數,則其所有位數數字的k次方與該數相等。

補充說明:
阿姆斯壯數(Armstrong number),又稱自戀數(Narcissistic number)(因為各數字 n 次方後加總又等於本身,感覺很自戀?)。
例如 153 可以滿足 1³ + 5³ + 3³ = 153,153 就是個阿姆斯壯數,阿姆斯壯數有 88 個,最大為 39 位數的 115132219018763992565095597973971522401,已證實超過 39 位數不存在阿姆斯壯數。

提示:若使用 Java 語言答題,請以「JP」開頭命名包含 main 靜態方法的 class,評測系統才能正確評分。

3. 輸入輸出:
輸入說明
一個整數n(0 < n < 1000)

輸出說明
所有小於n的阿姆斯壯數與其總和
範例輸入
999
範例輸出
1
2
3
4
5
6
7
8
9
153
370
371
407
1346
May

[hide]
C++

將字元轉整數來取得每一位數字:
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int n;
  4. int compute(int n)
  5. {
  6.     int total=0;
  7.     for(int i=1; i<n; i++)
  8.     {
  9.         int sum=0;
  10.         string str=to_string(i);
  11.         int len=str.length();
  12.         for(int j=0; j<len; j++)
  13.         {
  14.             int t=str[j]-'0';
  15.             sum+=pow(t, len);
  16.         }
  17.         if(sum==i)
  18.         {
  19.             cout<<i<<endl;
  20.             total+=i;
  21.         }
  22.     }
  23.     return total;
  24. }
  25. int main()
  26. {
  27.     cin>>n;
  28.     cout<<compute(n)<<endl;
  29.     return 0;
  30. }
複製代碼
以不斷取餘數來取得每一位數字:
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int n;
  4. int compute(int n)
  5. {
  6.     int total=0;
  7.     for(int i=1; i<n; i++)
  8.     {
  9.         int t=i, sum=0;
  10.         string str=to_string(t);
  11.         int len=str.length();
  12.         for(int j=0; j<len; j++)
  13.         {
  14.             sum+=pow(t%10, len);
  15.             t/=10;
  16.         }
  17.         if(sum==i)
  18.         {
  19.             cout<<i<<endl;
  20.             total+=i;
  21.         }
  22.     }
  23.     return total;
  24. }
  25. int main()
  26. {
  27.     cin>>n;
  28.     cout<<compute(n)<<endl;
  29.     return 0;
  30. }
複製代碼
May

TOP

返回列表