Advertisement
Solingen

z7.3.cpp

Dec 22nd, 2024
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. #include <iostream>
  2. #include "string.h"
  3. #include "array.h"
  4. using namespace std;
  5.  
  6. // Сумма собственных делителей
  7. long long sumOfDivisors(long long x)
  8. {
  9.     if (x < 2) return 0;
  10.     long long sum = 1;
  11.     for (long long d = 2; d*d <= x; d++)
  12.     {
  13.         if (x % d == 0)
  14.         {
  15.             sum += d;
  16.             long long pair = x / d;
  17.             if (pair != d) sum += pair;
  18.         }
  19.     }
  20.     return sum;
  21. }
  22.  
  23. bool isPerfect(long long x)
  24. {
  25.     if (x < 2) return false;
  26.     return sumOfDivisors(x) == x;
  27. }
  28.  
  29. int main()
  30. {
  31.     cout << "Сколько совершенных чисел вывести? ";
  32.     int N;
  33.     cin >> N;
  34.  
  35.     // Сохраним найденные совершенные числа в Array<long long>
  36.     Array<long long> perfects;
  37.  
  38.     long long candidate = 2;
  39.     while (perfects.size() < N)
  40.     {
  41.         if (isPerfect(candidate))
  42.         {
  43.             perfects.append(candidate);
  44.         }
  45.         candidate++;
  46.     }
  47.  
  48.     // Выведем их, используя String
  49.     for (int i = 0; i < perfects.size(); i++)
  50.     {
  51.         String msg = "Совершенное #";
  52.         msg = msg + to_string(i+1).c_str();
  53.         msg = msg + ": ";
  54.         msg = msg + to_string(perfects[i]).c_str();
  55.         cout << msg << endl;
  56.     }
  57.  
  58.     return 0;
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement