Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <bits/stdc++.h>
- using namespace std;
- /* Aluksi ohjelma kysyy positiivista lukua (tulo). Jos syötteeksi annetaan nolla
- * tai negatiivinen luku, ohjelma tulostaa “Only positive numbers accepted”.
- * Muussa tapauksessa ohjelma tulostaa tulon ja sen kaksi tekijää. Tekijöistä
- * pienempi tulostetaan ensin.
- */
- // prints contents of a list to terminal
- void print_list(list<int> l)
- {
- copy(l.begin(),
- l.end(),
- ostream_iterator<int>(cout, ", "));
- }
- int main()
- {
- string user_input;
- int number;
- cout << "Enter a positive number: ";
- getline(cin, user_input);
- // convert user string to int
- number = stoi(user_input);
- // basic input checking
- if (number < 1) {
- cout << "Only positive numbers accepted\n";
- return 0;
- }
- // check all numbers between 1 .. number if i is a factor
- // can't figure a way to do this otherwise
- int i;
- list<int> factors;
- for (i = 1; i <= number; i++) {
- if (number % i == 0) {
- factors.push_back(i);
- // cout << i << " is a factor of " << number << endl;
- }
- }
- // sort list just in case...
- factors.sort();
- // print_list(factors);
- // find closest numbers from the list
- int list_length = factors.size();
- // cout << list_length << " length of list.." << endl;
- int first_factor = 0;
- int second_factor = 0;
- for (i = 1; i < list_length; i++) {
- // if list has only 2 entries it's easy
- if (list_length == 2) {
- cout << number << " = 1 * " << number << endl;
- return 0;
- }
- }
- // Initialize iterator to list
- list<int>::iterator it = factors.begin();
- // Move the iterator
- if (list_length % 2 == 0) {
- advance(it, list_length/2-1);
- } else {
- advance(it, list_length/2);
- }
- first_factor = *it;
- // check if there's only one factor
- if (first_factor * first_factor == number) {
- second_factor = first_factor;
- } else {
- advance(it, 1);
- second_factor = *it;
- }
- // print the result
- cout << number << " = " << first_factor << " * " << second_factor << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement