Advertisement
H-a-y-K

Untitled

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