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?