vlatkovski

Faktorizacija

Jun 1st, 2017
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1. //THIS TOOK ME 2.5 HOURS. I HOPE YOU'RE HAPPY, MENDO. I HOPE YOU'RE HAPPY.
  2. #include <iostream>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. bool is_prime(int n) {
  8.     for (int i = 2; i <= n / 2; i++) {
  9.         if (n % i == 0) {
  10.             return false;
  11.         }
  12.     }
  13.     return true;
  14. }
  15.  
  16. int next_prime(int n) { //n is prime
  17.     do {
  18.         n += 2;
  19.     } while (!is_prime(n));
  20.  
  21.     return n;
  22. }
  23.  
  24. int main() {
  25.     int N;
  26.     cin >> N;
  27.  
  28.     //cout << is_prime(N);
  29.  
  30.     int N1 = N; //we will be doing all operations on this number
  31.     int factor = 2; //smallest prime number
  32.  
  33.     do {
  34.         static int exponent = 0;
  35.         static bool FIRST = true;
  36.  
  37.         if (N1 % factor == 0) { //is n1 divisible with the factor?
  38.             while (N1 % factor == 0) { //while above
  39.                 N1 /= factor; //divide n1 with the factor
  40.                 exponent++;
  41.             }
  42.  
  43.             if (FIRST) {
  44.                 cout << "(" << factor << "^" << exponent << ")";
  45.                 FIRST = false;
  46.             } else {
  47.                 cout << "*(" << factor << "^" << exponent << ")";
  48.             }
  49.  
  50.             exponent = 0;
  51.         }
  52.  
  53.         factor = factor == 2 ? 3 : next_prime(factor); //get next prime
  54.  
  55.     } while (N1 != 1);
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment