Skip to content
Related Articles

Related Articles

Improve Article

Find pair of consecutive Perfect Squares with difference K

  • Last Updated : 17 Sep, 2021

Given an integer K, the task is to find two consecutive perfect squares whose difference is K. If there don’t exist any such pairs of numbers, then print -1.

Examples:

Input: K = 5
Output: 4 9
Explaination:
So, 4 and 9 are the two perfect squares which differ by 5(= 9 – 4 = 5).

Input: K = 4
Output: -1

Naive Approach: The simple approach to solve the given problem is to traverse all the perfect squares and check if there exist any 2 such numbers whose difference is K, if found to be true, then prin those pairs. Otherwise, print -1.



Time Complexity: O(N)
Auxiliary Space: O(1)

Efficient Approach: The above approach can also be optimized by observing the difference between consecutive perfect squares as:

Perfect Squares:                1     4      9      16     25     …
Consecutive Difference:    3      5      7        9       …

From the above observation, the difference between consecutive perfect squares is in the order of consecutive odd numbers. Therefore, when the difference is even, then there exist no such pairs of numbers, hence print “-1”. Otherwise, the two number numbers are given by (K/2)2 and ((K + 1)/2)2.

Below is the implementation of the above approach:

C++14




// C++ program for the above approach
#include <iostream>
using namespace std;
 
// Function to find two consecutive
// perfect square numbers whose
// difference is N
void findPrimeNumbers(int N)
{
    int a, b;
    a = (N / 2) * (N / 2);
    b = ((N + 1) / 2) * ((N + 1) / 2);
 
    if ((N % 2) == 0)
        cout << "-1";
    else
        cout << a << " " << b;
}
 
// Driver Code
int main()
{
    int K = 5;
    findPrimeNumbers(K);
 
    return 0;
}

Java




// Java program for the above approach
import java.io.*;
 
class GFG {
 
    // Function to find two consecutive
    // perfect square numbers whose
    // difference is N
    static void findPrimeNumbers(int N)
    {
        int a, b;
        a = (N / 2) * (N / 2);
        b = ((N + 1) / 2) * ((N + 1) / 2);
 
        if ((N % 2) == 0)
            System.out.println("-1");
        else
            System.out.println(a + " " + b);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int K = 5;
        findPrimeNumbers(K);
    }
}
 
// This code is contributed by Dharanendra L V.

 
 

Output: 
4 9

 

 

Time Complexity: O(1)
Auxiliary Space: O(1)

 

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :