MSzopa

C++ 03.11.2022 Factorization

Nov 3rd, 2022
554
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. using namespace std;
  5.  
  6. bool IsPrime(int n) {
  7.     if (n < 2)
  8.         return false;
  9.     if (n == 2)
  10.         return true;
  11.     for (int i = 2; i < n; i++) {
  12.         if (n % i == 0)
  13.             return false;
  14.     }
  15.     return true;
  16. }
  17. vector<int> Factorize(int n) {
  18.     vector<int> ret;
  19.     int i = 2;
  20.     while (n > 1) {
  21.         if (n % i == 0) {
  22.             ret.push_back(i);
  23.             n /= i;
  24.         }
  25.         else
  26.             i++;
  27.     }
  28.     return ret;
  29. }
  30. int main()
  31. {
  32.     setlocale(LC_ALL, "Polish");
  33.     ifstream ff;
  34.     ofstream out;
  35.     out.open("wynik.txt");
  36.     ff.open("liczby.txt");
  37.     int c=0;
  38.     int maks = 0;
  39.     int liczba_maks = 0;
  40.     for (int i = 0; i < 500; i++) {
  41.         int a;
  42.         ff >> a;
  43.         /*if (!IsPrime(a)) {
  44.             cout << a << endl;
  45.             out << a << endl;
  46.             c++;
  47.         }*/
  48.         if (!IsPrime(a)) {
  49.             vector<int> liczby = Factorize(a);
  50.             int suma = 0;
  51.             for (int l : liczby)
  52.                 suma += l;
  53.             if (suma > maks)
  54.             {
  55.                 maks = suma;
  56.                 liczba_maks = a;
  57.             }
  58.  
  59.             cout << a << ": ";
  60.             for (int b : liczby) {
  61.                 cout << b << " ";
  62.             }
  63.             cout << endl;
  64.             c++;
  65.         }
  66.     }
  67.     cout << "Liczba, o największej sumie czynników to: ";
  68.     cout << liczba_maks <<endl;
  69.     out.flush();
  70.     out.close();
  71. }
Advertisement
Add Comment
Please, Sign In to add comment