example: all combinations of two integers whose product is 36
output:
1*36, 2*18, 3*12, 4*9, 6*6 etc..
I found this question on a book a while ago and I can't think of an approach. Please suggest the approach/code for this problem.
example: all combinations of two integers whose product is 36
output:
1*36, 2*18, 3*12, 4*9, 6*6 etc..
I found this question on a book a while ago and I can't think of an approach. Please suggest the approach/code for this problem.
You may do something like this:
#include <iostream>
int main()
{
    int n = 36;
    int biggestDivisor = n; // in case n is prime number, biggestDivisor is n
    for (int i = 1; i < biggestDivisor; i++) {
        if (n % i == 0) {
            std::cout << i << "*" << n / i << " ";
            biggestDivisor = n / i; // done so as to prevent 9 * 4 from getting printed if 4 * 9 is printed
        }
    }
}
Please note that the above approach works for all n > 1.
As per my understanding, you didn't want to print 9 * 4, in case 4 * 9 is already printed.
If you want to print all pairs, then do this:
#include <iostream>
#include <set>
int main()
{
    int n = 36;
    int biggestDivisor = n;
    std::set<std::pair<int, int> > combinationsList;
    for (int i = 1; i < biggestDivisor; i++) {
        if (n % i == 0) {
            combinationsList.insert(std::make_pair(i, n / i));
            combinationsList.insert(std::make_pair(n / i, i));
            biggestDivisor = n / i;
        }
    }
    for (const auto &ele: combinationsList) {
        std::cout << ele.first << "*" << ele.second << " ";
    }
}