Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- #include <array>
- #include <vector>
- #include <algorithm>
- bool is_perfect(int num)
- {
- int sum = 0;
- for (int i = 1; i < num; i++) // O(n)
- {
- // check if num is prime. prime numbers cannot be perfect.
- if (sum == 1 && i*i > num)
- return false;
- if (num % i == 0)
- sum += i;
- if (sum > num)
- return false;
- }
- return sum == num;
- }
- void test_case()
- {
- std::array<int, 4> perfect_nums = {6, 28, 496, 8128};
- std::vector<int> fails;
- for (int i = 1; i <= 8128; i++)
- {
- bool perfect = (std::find(perfect_nums.cbegin(),perfect_nums.cend(), i) != perfect_nums.cend());
- bool result = is_perfect(i);
- if (result == perfect)
- std::cout << "OK for " << i << " is perfect == " << result << std::endl;
- else
- {
- std::cout << "FAIL for " << i << ". The result is " << result << " but should be " << perfect << std::endl;
- fails.push_back(i);
- }
- }
- if (fails.size())
- {
- std::cout << "\n\nTest failed for the number(s) ";
- for (int fail : fails)
- std::cout << fail << std::endl;
- }
- else
- std::cout << "\n\nThere are no failed tests!";
- }
- int main() {
- test_case();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement