Advertisement
H-a-y-K

Untitled

Nov 26th, 2020
336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <array>
  4. #include <vector>
  5. #include <algorithm>
  6.  
  7. bool is_perfect(int num)
  8. {
  9.     int sum = 0;
  10.  
  11.     for (int i = 1; i < num; i++) // O(n)
  12.     {
  13.         // check if num is prime. prime numbers cannot be perfect.
  14.         if (sum == 1 && i*i > num)
  15.             return false;
  16.  
  17.         if (num % i == 0)
  18.             sum += i;
  19.  
  20.         if (sum > num)
  21.             return false;
  22.     }
  23.  
  24.     return sum == num;
  25. }
  26.  
  27. void test_case()
  28. {
  29.     std::array<int, 4> perfect_nums = {6, 28, 496, 8128};
  30.     std::vector<int> fails;
  31.  
  32.     for (int i = 1; i <= 8128; i++)
  33.     {
  34.         bool perfect = (std::find(perfect_nums.cbegin(),perfect_nums.cend(), i) != perfect_nums.cend());
  35.  
  36.         bool result = is_perfect(i);
  37.  
  38.         if (result == perfect)
  39.             std::cout << "OK for " << i << " is perfect == " << result << std::endl;
  40.         else
  41.         {
  42.             std::cout << "FAIL for " << i << ". The result is " << result << " but should be " << perfect << std::endl;
  43.             fails.push_back(i);
  44.         }
  45.     }
  46.  
  47.     if (fails.size())
  48.     {
  49.         std::cout << "\n\nTest failed for the number(s) ";
  50.         for (int fail : fails)
  51.             std::cout << fail << std::endl;
  52.     }
  53.     else
  54.         std::cout << "\n\nThere are no failed tests!";
  55. }
  56.  
  57. int main() {
  58.     test_case();
  59.     return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement