Search code examples
c++algorithmfactors

C++ - Factors of an integer displayed in pairs


I have the code that displays the factors of an inputted integer:

#include <iostream>
using namespace std;

int main() {

    int value;
    cout << "Enter a value ";
    cin >> value;

    for (int i = 1; i <= value; i++) {
        if(value % i == 0) {
            cout << i << " ";
        }
    }
}

which displays

1 2 3 6

if the input is 6.

However, I am not too sure how to get the result as

2,3||1,6||

Can anyone provide any hints on how I can achieve this?


My professor is just going over MOD so I am not sure if this requires a topic that hasn't been covered yet.


Solution

  • Change your code as follows :

    for (int i=1;i<=sqrt(value);i++){
            if(value%i==0){
            cout<<i<<","<<value/i;
        }
    

    Include <math.h> for sqrt()

    Or you could use i * i <= value