Advertisement
Hydreigon_Lord

Factor Lister and Summer

Jul 2nd, 2020
1,604
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. //Hydreigon_Lord
  2. //This program generates all the factors of a given number.
  3.  
  4. #include <iostream>
  5. #include <vector>
  6. #define POSITION (factors.begin() + pos)
  7. using namespace std;
  8.  
  9. int main()
  10. {
  11.     unsigned long long num;
  12.     cout << "Enter a number: ";
  13.     cin >> num;
  14.     vector<unsigned long long> factors;
  15.     factors.push_back(1);
  16.     if (num != 1)
  17.     {
  18.         factors.push_back(num);
  19.         int pos = 1;
  20.         for (unsigned long long i = 2; i * i <= num; i++)
  21.         {
  22.             if (i * i == num)
  23.                 factors.insert(POSITION, i);
  24.             else
  25.             {
  26.                 if (num % i == 0)
  27.                 {
  28.                     factors.insert(POSITION, num / i);
  29.                     factors.insert(POSITION, i);
  30.                     pos++;
  31.                 }
  32.             }
  33.         }
  34.     }
  35.     cout << num << " has " << factors.size() << " factors: ";
  36.     unsigned long long sum = 0;
  37.     for (unsigned long long f: factors)
  38.     {
  39.         cout << f << " ";
  40.         sum += f;
  41.     }
  42.     cout << endl;
  43.     cout << "The sum of the factors is: " << sum << endl;
  44.     double ratio = (double)sum / num;
  45.     cout << "The ratio of the factor sum to the number is: " << ratio << endl;
  46.     return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement