Skip to content

Commit 1ff4efc

Browse files
committed
perfect number
1 parent e5dad3f commit 1ff4efc

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,7 @@
201201
* [Lcm](https://github.com/TheAlgorithms/C/blob/HEAD/math/lcm.c)
202202
* [Lerp](https://github.com/TheAlgorithms/C/blob/HEAD/math/lerp.c)
203203
* [Palindrome](https://github.com/TheAlgorithms/C/blob/HEAD/math/palindrome.c)
204+
* [Perfect Numbers](https://github.com/TheAlgorithms/C/blob/HEAD/math/perfect_numbers.c)
204205
* [Prime](https://github.com/TheAlgorithms/C/blob/HEAD/math/prime.c)
205206
* [Prime Factoriziation](https://github.com/TheAlgorithms/C/blob/HEAD/math/prime_factoriziation.c)
206207
* [Prime Sieve](https://github.com/TheAlgorithms/C/blob/HEAD/math/prime_sieve.c)

math/perfect_numbers.c

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <stdio.h>
2+
#include <stdbool.h>
3+
#include <assert.h>
4+
#include <math.h>
5+
6+
/* This function returns true
7+
if the submitted number is perfect,
8+
false if it is not.
9+
10+
A perfect number is a positive integer that is
11+
equal to the sum of its positive proper
12+
divisors, excluding the number itself.
13+
14+
About perfect numbers: https://en.wikipedia.org/wiki/Perfect_number
15+
16+
@author Marco https://github.com/MaarcooC
17+
@param int $number
18+
@return bool */
19+
20+
bool isPerfect(int number) {
21+
// Handle edge cases: negative numbers and zero
22+
if (number <= 1) {
23+
return false; // 0 and negative numbers are not perfect
24+
}
25+
26+
int sumOfDivisors = 1; // Initialize the sum of divisors with 1
27+
28+
// Check for divisors from 2 to sqrt(number)
29+
for (int i = 2; i <= sqrt(number); i++) {
30+
if (number % i == 0) { // If it is divisible
31+
sumOfDivisors += i; // Add i to the sum of divisors
32+
if (i != number / i) {
33+
sumOfDivisors += number / i; // Add the corresponding divisor
34+
}
35+
}
36+
}
37+
38+
return sumOfDivisors == number;
39+
}
40+
41+
// tests
42+
void tests() {
43+
assert(isPerfect(1) == false);
44+
assert(isPerfect(6) == true);
45+
assert(isPerfect(28) == true);
46+
assert(isPerfect(-1) == false);
47+
assert(isPerfect(0) == false);
48+
assert(isPerfect(496) == true);
49+
}
50+
51+
int main() {
52+
tests();
53+
printf("All tests passed!");
54+
return 0;
55+
}

0 commit comments

Comments
 (0)