Advertisement
Solingen

z9.2.cpp

Dec 22nd, 2024
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <cmath>
  4. using namespace std;
  5.  
  6. // Возвращает список простых множителей числа n
  7. vector<long long> factorize(long long n)
  8. {
  9.     vector<long long> factors;
  10.     for (long long d = 2; d * d <= n; d++)
  11.     {
  12.         while (n % d == 0)
  13.         {
  14.             factors.push_back(d);
  15.             n /= d;
  16.         }
  17.     }
  18.     if (n > 1) factors.push_back(n);
  19.     return factors;
  20. }
  21.  
  22. int main()
  23. {
  24.     long long N;
  25.     cout << "Введите число (<=1e9): ";
  26.     cin >> N;
  27.  
  28.     vector<long long> f = factorize(N);
  29.  
  30.     // Формируем красивый вывод: например, 100 -> 2^2 * 5^2
  31.     // Для этого посчитаем кратность каждого множителя
  32.     if (f.empty())
  33.     {
  34.         cout << "Нет множителей (N=0 или 1?)\n";
  35.         return 0;
  36.     }
  37.  
  38.     // f может быть, например, [2, 2, 5, 5]
  39.     // Сгруппируем
  40.     long long current = f[0];
  41.     int count = 1;
  42.     for (int i = 1; i < (int)f.size(); i++)
  43.     {
  44.         if (f[i] == current)
  45.         {
  46.             count++;
  47.         }
  48.         else
  49.         {
  50.             // Выводим накопленное
  51.             cout << current;
  52.             if (count > 1) cout << "^" << count;
  53.             cout << " * ";
  54.             // Обновляем
  55.             current = f[i];
  56.             count = 1;
  57.         }
  58.     }
  59.     // Выводим последнее
  60.     cout << current;
  61.     if (count > 1) cout << "^" << count;
  62.     cout << endl;
  63.  
  64.     return 0;
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement