用 C++ 计算一个数的所有完全除数
在本教程中,我们将讨论一个程序,该程序用于找出某个数的所有完全除数。
为此,我们将得到一个数。我们的任务是计算该给定数的所有完全除数。
示例
#include<bits/stdc++.h> using namespace std; //checking perfect square bool if_psquare(int n){ int sq = (int) sqrt(n); return (n == sq * sq); } //returning count of perfect divisors 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
广告