MeehoweCK

Untitled

Jun 6th, 2024
384
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include <iostream>
  2. #include <sstream>
  3. #include <vector>
  4.  
  5. using ulong = unsigned long long;
  6. using vector = std::vector<std::pair<ulong, int>>;
  7.  
  8. std::string wypisz_czynniki(const vector& czynniki) {
  9.     auto d{ czynniki.size() - 1};
  10.     std::stringstream result{};
  11.     auto out{ [czynniki, &result](const auto x) {
  12.         result << czynniki[x].first;
  13.         if (czynniki[x].second > 1) {
  14.             result << '^' << czynniki[x].second;
  15.         }
  16.     } };
  17.     for (int i{}; i < d; ++i) {
  18.         out(i);
  19.         result << " * ";
  20.     }
  21.     out(d);
  22.     return result.str();
  23. }
  24.  
  25. ulong pobierz_liczbe() {
  26.     std::cout << "Podaj liczbe naturalna lub 0 jesli chcesz wyjsc: ";
  27.     ulong result;
  28.     std::cin >> result;
  29.     while (std::cin.fail()) {
  30.         std::cout << "\tPodales nieprawidlowa liczbe, wpisz jeszcze raz: ";
  31.         std::cin.clear();
  32.         std::cin.ignore(999999, '\n');
  33.         std::cin >> result;
  34.     }
  35.     return result;
  36. }
  37.  
  38. bool rozloz_liczbe() {
  39.     auto liczba{ pobierz_liczbe() };
  40.     if (liczba == 0) {
  41.         return false;
  42.     }
  43.     const auto rozkladana{ liczba };
  44.     ulong dzielnik{ 2 };
  45.     vector czynniki{};
  46.     while (liczba > 1) {
  47.         if (liczba % dzielnik == 0) {
  48.             auto p{ std::make_pair(dzielnik, 0) };
  49.             do {
  50.                 ++(p.second);
  51.                 liczba /= dzielnik;
  52.             } while (liczba % dzielnik == 0);
  53.             czynniki.push_back(p);
  54.         }
  55.         ++dzielnik;
  56.     }
  57.     std::cout << '\t' << rozkladana << " = " << wypisz_czynniki(czynniki) << "\n\n";
  58.     return true;
  59. }
  60.  
  61. int main() {
  62.     while (rozloz_liczbe()) {};
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment