C++ 中的近乎完美數


近乎完美數也被稱為最虧缺數或稍虧數,它是一個數,其中所有因子(包括 1 和該數本身)的和應等於 2n-1

在此問題中,我們將定義一個演算法來檢查一個數是否是一個近乎完美數。

我們舉個例子來更好地理解這個概念,

Input : 16
Output : yes
Explanation :
Divisors of 16 are 1, 2, 4, 8, 16.
Sum = 1 + 2 + 4 + 8 + 16 = 31
n = 16 ; 2n-1 = 2*16 - 1 = 31

Input : 12
Output : No
Explanation :
Divisors of 12 are 1, 2, 3, 4, 6, 12.
Sum = 1+2+3+4+6+12 = 26
n = 12 ; 2n-1 = 2*12 - 1 = 23

現在,檢查給定數是否為近乎完美數的問題已使用近乎完美數的邏輯解決,即數字所有因子的和等於 2n -1

演算法

Step 1 : Calculate the sum of all divisors of the number.
Step 2 : Calculate the value of val = 2n-1.
Step 3 : if sum == val -> print “YES”
Step 4 : else print “NO”

示例

 即時演示

#include <iostream>
using namespace std;
void almostPerfectNumber(int n) ;
int main(){
   int n = 16;
   cout<<"Is "<<n<<" an almost perfect number ?\n";
   almostPerfectNumber(n) ;
}
void almostPerfectNumber(int n){
   int divisors = 0;
   for (int i = 1; i <= n; i++) {
      if (n % i == 0)
         divisors += i;
   }
   if (divisors == 2 * n - 1)
      cout<<"YES";
   else
   cout<<"NO";
}

輸出

Is 16 an almost perfect number ?
YES

更新於: 16-Oct-2019

159 瀏覽

開啟你的事業

完成本課程,取得認證

開始
廣告
© . All rights reserved.