0

I am working on a code to print all the numbers which have their LCM as 240. Now this is pretty easy, write 2 for loops and you're done. I have provided the code below. What I want now is to remove duplicate pairs. For example, if I have already printed (16,30) I dont want to print (30,16).

So what I have thought to resolve this is modify the 2nd indices to have an upper limit equal to the 1st index.


using namespace std; 


int findLCM(int a, int b) 
{ 
    int lar = max(a, b); 
    int small = min(a, b); 
    for (int i = lar; ; i += lar) { 
        if (i % small == 0) 
            return i; 
    } 
} 

int main() 
{ 
    int a = 5, b = 7,s=0; 
    for(int i=1;i<=360;i++){
        for(int j=1;j<=i;j++){
            if(findLCM(i,j)==360){
                cout<<"("<<i<<","<<j<<")"<<endl;
                s++;
            }
        }
    } 
  cout<<s;
    return 0; 
} 

\\modified code

using namespace std; 


{ 
    int lar = max(a, b); 
    int small = min(a, b); 
    for (int i = lar; ; i += lar) { 
        if (i % small == 0) 
            return i; 
    } 
} 


int main() 
{ 
    int a = 5, b = 7,s=0; 
    for(int i=1;i<=240;i++){
        for(int j=1;j<=i;j++){
            if(findLCM(i,j)==240){
                cout<<"("<<i<<","<<j<<")"<<endl;
                s++;
            }
        }
    } 
  cout<<s;
    return 0; 
} 

So I found that this does seem to work. Is this modification in the loop enough to ensure that duplicate pairs aren't printed?

Ray Penber
  • 29
  • 8
  • 1
    What makes you think your fix is not good enough? Since now `j <= i`, it's impossible for both `(a,b)` and `(b,a)` to be printed (unless `a == b`), since in at least one of them `j` would have to be greater than `i`. – HolyBlackCat Oct 25 '19 at 12:10
  • Don't write "I found that this does seem to work". Write what happened in particular that shouldn't. – Aziuth Oct 25 '19 at 13:47
  • @HolyBlackCat I wasn't sure if all the cases were covered or if there was a better/efficient way to do it. – Ray Penber Oct 25 '19 at 19:17

0 Answers0