Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C Program to Check if count of divisors is even or odd?
Given a number “n” as an input, this program finds whether the total number of divisors of n is even or odd. A divisor of a number is any integer that divides the number without leaving a remainder.
An even number is an integer that is exactly divisible by 2. Example: 0, 8, -24
An odd number is an integer that is not exactly divisible by 2. Example: 1, 7, -11, 15
Syntax
// Count divisors and check if count is even or odd
for (int i = 1; i <= sqrt(n); i++) {
if (n % i == 0) {
count += (n / i == i) ? 1 : 2;
}
}
Example: Basic Approach
This approach finds all divisors by iterating up to the square root of n and counting pairs of divisors −
#include <stdio.h>
#include <math.h>
int main() {
int n = 10;
int count = 0;
printf("Finding divisors of %d:<br>", n);
for (int i = 1; i <= sqrt(n); i++) {
if (n % i == 0) {
if (n / i == i) {
printf("%d ", i);
count += 1; // Perfect square case
} else {
printf("%d %d ", i, n/i);
count += 2; // Two different divisors
}
}
}
printf("\nTotal divisors: %d<br>", count);
if (count % 2 == 0)
printf("Count is Even<br>");
else
printf("Count is Odd<br>");
return 0;
}
Finding divisors of 10: 1 10 2 5 Total divisors: 4 Count is Even
Example: Testing Multiple Numbers
Let's test the logic with different numbers to see the pattern −
#include <stdio.h>
#include <math.h>
int countDivisors(int n) {
int count = 0;
for (int i = 1; i <= sqrt(n); i++) {
if (n % i == 0) {
count += (n / i == i) ? 1 : 2;
}
}
return count;
}
int main() {
int numbers[] = {6, 9, 12, 16, 25};
int size = sizeof(numbers) / sizeof(numbers[0]);
for (int i = 0; i < size; i++) {
int n = numbers[i];
int divisorCount = countDivisors(n);
printf("Number: %d, Divisors: %d, ", n, divisorCount);
printf("Count is %s<br>", (divisorCount % 2 == 0) ? "Even" : "Odd");
}
return 0;
}
Number: 6, Divisors: 4, Count is Even Number: 9, Divisors: 3, Count is Odd Number: 12, Divisors: 6, Count is Even Number: 16, Divisors: 5, Count is Odd Number: 25, Divisors: 3, Count is Odd
How It Works
- The algorithm iterates from 1 to ?n to find divisor pairs efficiently
- For each divisor i found, there's a corresponding divisor n/i
- If i = n/i (perfect square case), we count it once; otherwise, we count both
- Perfect squares always have an odd number of divisors
Key Points
- Time Complexity: O(?n) for finding all divisors
- Space Complexity: O(1) constant extra space
- Perfect squares (4, 9, 16, 25...) always have odd divisor counts
- Non-perfect squares always have even divisor counts
Conclusion
This program efficiently determines if the count of divisors is even or odd using square root optimization. Perfect squares have odd divisor counts, while all other numbers have even divisor counts.
