Advertisement
Ihmemies

Untitled

Sep 2nd, 2022
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.25 KB | None | 0 0
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3.  
  4. using namespace std;
  5.  
  6. /* Aluksi ohjelma kysyy positiivista lukua (tulo). Jos syötteeksi annetaan nolla
  7.  * tai negatiivinen luku, ohjelma tulostaa “Only positive numbers accepted”.
  8.  * Muussa tapauksessa ohjelma tulostaa tulon ja sen kaksi tekijää. Tekijöistä
  9.  * pienempi tulostetaan ensin.
  10.  */
  11.  
  12. // prints contents of a list to terminal
  13. void print_list(list<int> l)
  14. {
  15.     copy(l.begin(),
  16.     l.end(),
  17.     ostream_iterator<int>(cout, ", "));
  18. }
  19.  
  20. int main()
  21. {
  22.     string user_input;
  23.     int number;
  24.  
  25.     cout << "Enter a positive number: ";
  26.     getline(cin, user_input);
  27.  
  28.     // convert user string to int
  29.     number = stoi(user_input);
  30.  
  31.     // basic input checking
  32.     if (number < 1) {
  33.         cout << "Only positive numbers accepted\n";
  34.         return 0;
  35.     }
  36.  
  37.     // check all numbers between 1 .. number if i is a factor
  38.     // can't figure a way to do this otherwise
  39.     int i;
  40.     list<int> factors;
  41.  
  42.     for (i = 1; i <= number; i++) {
  43.         if (number % i == 0) {
  44.             factors.push_back(i);
  45.             // cout << i << " is a factor of " << number << endl;
  46.         }
  47.     }
  48.  
  49.     // sort list just in case...
  50.     factors.sort();
  51.     // print_list(factors);
  52.  
  53.     // find closest numbers from the list
  54.     int list_length = factors.size();
  55.     // cout << list_length << " length of list.." << endl;
  56.  
  57.     int first_factor = 0;
  58.     int second_factor = 0;
  59.  
  60.     for (i = 1; i < list_length; i++) {
  61.         // if list has only 2 entries it's easy
  62.         if (list_length == 2) {
  63.             cout << number << " = 1 * " << number << endl;
  64.             return 0;
  65.         }
  66.     }
  67.  
  68.     // Initialize iterator to list
  69.     list<int>::iterator it = factors.begin();
  70.  
  71.     // Move the iterator
  72.     if (list_length % 2 == 0) {
  73.         advance(it, list_length/2-1);
  74.     } else {
  75.         advance(it, list_length/2);
  76.     }
  77.     first_factor = *it;
  78.  
  79.     // check if there's only one factor
  80.     if (first_factor * first_factor == number) {
  81.         second_factor = first_factor;
  82.     } else {
  83.         advance(it, 1);
  84.         second_factor = *it;
  85.     }
  86.  
  87.     // print the result
  88.     cout << number << " = " << first_factor << " * " << second_factor << endl;
  89.  
  90.     return 0;
  91. }
  92.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement