C Program to Check if count of divisors is even or odd
Last Updated :
23 Nov, 2022
Given a number “n”, find its total number of divisors is even or odd.
Examples :
Input : n = 10
Output : Even
Input: n = 100
Output: Odd
Input: n = 125
Output: Even
A naive approach would be to find all the divisors and then see if the total number of divisors is even or odd.
C
#include <math.h>
#include <stdio.h>
void countDivisors( int n)
{
int count = 0;
for ( int i = 1; i <= sqrt (n) + 1; i++) {
if (n % i == 0)
count += (n / i == i) ? 1 : 2;
}
if (count % 2 == 0)
printf ( "Even\n" );
else
printf ( "Odd\n" );
}
int main()
{
printf ( "The count of divisor: " );
countDivisors(10);
return 0;
}
|
Output:
The count of divisor: Even
Time Complexity: O(sqrt(n))
Auxiliary Space: O(1)
Efficient Solution: We can observe that the number of divisors is odd only in case of perfect squares. Hence the best solution would be to check if the given number is perfect square or not. If it’s a perfect square, then the number of divisors would be odd, else it’d be even.
CPP
#include <bits/stdc++.h>
using namespace std;
void countDivisors( int n)
{
int root_n = sqrt (n);
if (root_n * root_n == n)
printf ( "Odd\n" );
else
printf ( "Even\n" );
}
int main()
{
cout << "The count of divisors of 10 is: \n" ;
countDivisors(10);
return 0;
}
|
Output:
The count of divisors of 10 is:
Even
Time Complexity: O(log(n))
Auxiliary Space: O(1). If recursive call stack will be considered then it would be log(n).
Please refer complete article on Check if count of divisors is even or odd for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...