Count all perfect divisors of a number in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find the number of all perfect divisors of a number.

For this we will be provided with a number. Our task is to count all the perfect divisors of that given number.

Example

#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;
}

Output

Total perfect divisors of 16 = 3
Total perfect divisors of 12 = 2
raja
Published on 10-Feb-2020 11:27:34
Advertisements