Advertisement
Solingen

z9.3.cpp

Dec 22nd, 2024
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.08 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include "string.h"
  4. #include "array.h"
  5. using namespace std;
  6.  
  7. Array<long long> factorize(long long n)
  8. {
  9.     Array<long long> arr;
  10.     for (long long d = 2; d * d <= n; d++)
  11.     {
  12.         while (n % d == 0)
  13.         {
  14.             arr.append(d);
  15.             n /= d;
  16.         }
  17.     }
  18.     if (n > 1)
  19.     {
  20.         arr.append(n);
  21.     }
  22.     return arr;
  23. }
  24.  
  25. int main()
  26. {
  27.     cout << "Введите число (<=1e9): ";
  28.     long long N;
  29.     cin >> N;
  30.  
  31.     Array<long long> factors = factorize(N);
  32.  
  33.     if (factors.size() == 0)
  34.     {
  35.         cout << "Число " << N << " не имеет простых множителей (возможно это 1?)\n";
  36.         return 0;
  37.     }
  38.  
  39.     // Оформим вывод в виде строки, например "2^2 * 5^2"
  40.     String output;
  41.     long long currentFactor = factors[0];
  42.     int count = 1;
  43.     for (int i = 1; i < factors.size(); i++)
  44.     {
  45.         if (factors[i] == currentFactor)
  46.         {
  47.             count++;
  48.         }
  49.         else
  50.         {
  51.             // Добавим к output
  52.             String part = to_string(currentFactor).c_str();
  53.             if (count > 1)
  54.             {
  55.                 part = part + "^";
  56.                 part = part + to_string(count).c_str();
  57.             }
  58.             // Если вывод уже не пуст, добавим " * "
  59.             if (output.length() > 0)
  60.             {
  61.                 output = output + " * ";
  62.             }
  63.             output = output + part;
  64.  
  65.             // Обновим
  66.             currentFactor = factors[i];
  67.             count = 1;
  68.         }
  69.     }
  70.     // Не забыть последнее "скопившееся"
  71.     {
  72.         String part = to_string(currentFactor).c_str();
  73.         if (count > 1)
  74.         {
  75.             part = part + "^";
  76.             part = part + to_string(count).c_str();
  77.         }
  78.         if (output.length() > 0) output = output + " * ";
  79.         output = output + part;
  80.     }
  81.  
  82.     cout << "Разложение: " << output << endl;
  83.  
  84.     return 0;
  85. }
  86.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement