C++ program to find unique pairs such that each element is less than or equal to N

C++Server Side ProgrammingProgramming

In this article, we will be discussing a program to find unique pairs of numbers having elements less than or equal to N and following some certain conditions −

  • The square of difference between the two numbers must be equal to the LCM of those two numbers.

  • The HCF of those two numbers can be represented as a product of any two consecutive numbers.

The best approach to solve this problem would be to take two consecutive numbers (starting from 1) and finding the multiples of product of those numbers. Then among the multiples, to specify to one pair of numbers we need to check if the numbers in the pair satisfy the first given condition.

For example, take the case of 2 and 3. Their product would be 6. Now if we go on with the multiples of 6, we would get 6, 12, 18, 24 … Taking two numbers at a time, we check if the square of difference between two consecutive numbers (36 in this case) is equal to the LCM of those numbers. We finally get the pair in this case to be 12 and 18.

Generalizing the equation, we get the two numbers to be Z * (Z*(Z+1)) and (Z+1) * (Z*(Z+1)) where Z is the first number in the HCF (consecutive pair product).

Finally using the condition that the values should be less than N, we get

(Z+1) * (Z*(Z+1)) <= N or Z3 + (2*Z2) + Z <= N.


 Live Demo

#include <iostream>
using namespace std;
int main() {
   int N = 489, pairs, i = 1;
   //counting the number of pairs having elements less than N
   while((i*i*i) + (2*i*i) + i <= N) {
   pairs = i;
   cout << "Pairs :" << endl;
   //printing the two elements of the pair
   for(int j = 1; j < pairs; j++) {
      cout << j*(j*(j+1)) << " " << (j+1)*(j*(j+1)) << endl;
   return 0;


Pairs :
2 4
12 18
36 48
80 100
150 180
252 294
392 448
Published on 03-Oct-2019 11:15:56