计算C ++中一个数字的所有完美除数

在本教程中,我们将讨论一个程序,以找到一个数字的所有理想除数的数量。

为此,我们将提供一个号码。我们的任务是计算给定数字的所有完美除数。

示例

#include<bits/stdc++.h>

using namespace std;

//检查完美正方形

bool if_psquare(int n){

   int sq = (int) sqrt(n);

   return (n == sq * sq);

}

//返回完美除数的计数

int count_pdivisors(int n){

   int count = 0;

   for (int i=1; i*i <= n; ++i){

      if (n%i == 0){

         if (if_psquare(i))

            ++count;

         if (n/i != i && if_psquare(n/i))

            ++count;

      }

   }

   return count;

}

int main(){

   int n = 16;

   cout << "Total perfect divisors of " << n << " = " << count_pdivisors(n) << "\n";

   n = 12;

   cout << "Total perfect divisors of " << n << " = " << count_pdivisors(n);

   return 0;

}

输出结果

Total perfect divisors of 16 = 3

Total perfect divisors of 12 = 2

以上是 计算C ++中一个数字的所有完美除数 的全部内容, 来源链接: utcz.com/z/357728.html

回到顶部