Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perfect number #1418

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@
* [Lcm](https://github.com/TheAlgorithms/C/blob/HEAD/math/lcm.c)
* [Lerp](https://github.com/TheAlgorithms/C/blob/HEAD/math/lerp.c)
* [Palindrome](https://github.com/TheAlgorithms/C/blob/HEAD/math/palindrome.c)
* [Perfect Numbers](https://github.com/TheAlgorithms/C/blob/HEAD/math/perfect_numbers.c)
* [Prime](https://github.com/TheAlgorithms/C/blob/HEAD/math/prime.c)
* [Prime Factoriziation](https://github.com/TheAlgorithms/C/blob/HEAD/math/prime_factoriziation.c)
* [Prime Sieve](https://github.com/TheAlgorithms/C/blob/HEAD/math/prime_sieve.c)
Expand Down
55 changes: 55 additions & 0 deletions math/perfect_numbers.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#include <stdio.h>
#include <stdbool.h>
#include <assert.h>
#include <math.h>

/* This function returns true
if the submitted number is perfect,
false if it is not.

A perfect number is a positive integer that is
equal to the sum of its positive proper
divisors, excluding the number itself.

About perfect numbers: https://en.wikipedia.org/wiki/Perfect_number

@author Marco https://github.com/MaarcooC
@param int $number
@return bool */

bool isPerfect(int number) {
// Handle edge cases: negative numbers and zero
if (number <= 1) {
return false; // 0 and negative numbers are not perfect
}

int sumOfDivisors = 1; // Initialize the sum of divisors with 1

// Check for divisors from 2 to sqrt(number)
for (int i = 2; i <= sqrt(number); i++) {
if (number % i == 0) { // If it is divisible
sumOfDivisors += i; // Add i to the sum of divisors
if (i != number / i) {
sumOfDivisors += number / i; // Add the corresponding divisor
}
}
}

return sumOfDivisors == number;
}

// tests
void tests() {
assert(isPerfect(1) == false);
assert(isPerfect(6) == true);
assert(isPerfect(28) == true);
assert(isPerfect(-1) == false);
assert(isPerfect(0) == false);
assert(isPerfect(496) == true);
}

int main() {
tests();
printf("All tests passed!");
return 0;
}
Loading