Find smallest perfect square number A such that N + A is also a perfect square number
Last Updated :
16 Mar, 2023
Given a positive number N. The task is to find out the smallest perfect square number A such that N + A is also a perfect square number or return -1.
Examples:
Input: N = 3
Output: 1
Explanation:
As 1 + 3 = 4 = 22
Input: N=1
Output: -1
Naive Approach:
Traverse M from {1, 2, 3, 4, 5...} and check whether (N + M * M) is a perfect square number or not.
C++
// C++ code of above approach
#include<bits/stdc++.h>
using namespace std;
// Check if number is perfect square
// or not.
bool checkperfectsquare(int n)
{
// If ceil and floor are equal
// the number is a perfect
// square
if (ceil((double)sqrt(n)) == floor((double)sqrt(n))) {
return true;
}
else {
return false;
}
}
// Function to find out the smallest
// perfect square X which when added to N
// yields another perfect square number.
long SmallestPerfectSquare(long N){
long X = (long)1e9;
long ans=-1;
for(int i=1;i<=X;i++)
{
if(checkperfectsquare(N+i*i))
{
ans=i*i;
break;
}
}
return ans;
}
// Driver code
int main()
{
long N = 3;
cout << SmallestPerfectSquare(N);
return 0;
}
// This code is contributed by Utkarsh Kumar.
Java
// Java code of above approach
import java.util.*;
class GFG {
// Check if number is perfect square
// or not.
public static boolean checkperfectsquare(long n)
{
// If ceil and floor are equal
// the number is a perfect
// square
if (Math.ceil(Math.sqrt(n))
== Math.floor(Math.sqrt(n))) {
return true;
}
else {
return false;
}
}
// Function to find out the smallest
// perfect square X which when added to N
// yields another perfect square number.
public static long SmallestPerfectSquare(long N)
{
long X = (long)1e9;
long ans = -1;
for (int i = 1; i <= X; i++) {
if (checkperfectsquare(N + (long)i * i)) {
ans = i * i;
break;
}
}
return ans;
}
// Driver code
public static void main(String[] args)
{
long N = 3;
System.out.println(SmallestPerfectSquare(N));
}
}
// This code is contributed by prasad264
Python3
# Python code of above approach
import math
# Check if number is perfect square
# or not.
def checkperfectsquare(n):
# If ceil and floor are equal
# the number is a perfect
# square
if math.ceil(math.sqrt(n)) == math.floor(math.sqrt(n)):
return True
else:
return False
# Function to find out the smallest
# perfect square X which when added to N
# yields another perfect square number.
def SmallestPerfectSquare(N):
X = int(1e9)
ans = -1
for i in range(1, X+1):
if checkperfectsquare(N + i*i):
ans = i*i
break
return ans
# Driver code
N = 3
print(SmallestPerfectSquare(N))
# This code is contributed by prasad264
C#
// C# code of above approach
using System;
class Program
{
// Check if number is perfect square or not.
static bool CheckPerfectSquare(long n)
{
// If ceil and floor are equal the number is a perfect square.
if (Math.Ceiling(Math.Sqrt(n)) == Math.Floor(Math.Sqrt(n)))
{
return true;
}
else
{
return false;
}
}
// Function to find out the smallest perfect square X
// which when added to N yields another perfect square number.
static long SmallestPerfectSquare(long N)
{
long X = (long)1e9;
long ans = -1;
for (int i = 1; i <= X; i++)
{
if (CheckPerfectSquare(N + i * i))
{
ans = i * i;
break;
}
}
return ans;
}
// Driver code
static void Main()
{
long N = 3;
Console.WriteLine(SmallestPerfectSquare(N));
}
}
JavaScript
// Javascript code of above approach
function checkperfectsquare(n) {
// If ceil and floor are equal
// the number is a perfect
// square
if (Math.ceil(Math.sqrt(n)) == Math.floor(Math.sqrt(n))) {
return true;
} else {
return false;
}
}
function SmallestPerfectSquare(N) {
const X = 1000000000;
let ans = -1;
for (let i = 1; i <= X; i++) {
if (checkperfectsquare(N + i * i)) {
ans = i * i;
break;
}
}
return ans;
}
const N = 3;
console.log(SmallestPerfectSquare(N));
Time complexity: O(X*log(X)) where X=1e9 here
Auxiliary Space: O(1)
Efficient Approach:
- On observing, we have an equation like:
- N + (X * X) = (M * M) where N is given and M and X are unknown.
- We can rearrange it and get:
- N = (M * M) - (X * X)
- N = (M + X) * (M - X)
- Now we can see that for obtaining N, we need to find the factor of N.The factor of N can be obtained in O(N) time. But it can be optimized to O(N^1/2) by this method.
- Let the factor of N be a and b = (N / a). So, from the above equation a = (M - X) and b = (M + X), and after solving this we can obtain the value of X = (b - a)/2.
Below is the implementation of the above approach:
C++
// C++ code to find out the smallest
// perfect square X which when added to N
// yields another perfect square number.
#include<bits/stdc++.h>
using namespace std;
long SmallestPerfectSquare(long N){
// X is the smallest perfect
// square number
long X = (long)1e9;
long ans;
// Loop from 1 to square root of N
for(int i = 1; i < sqrt(N); i++)
{
// Condition to check whether i
// is factor of N or not
if (N % i == 0)
{
long a = i;
long b = N / i;
// Condition to check whether
// factors satisfies the
// equation or not
if((b - a != 0) && ((b - a) % 2 == 0))
{
// Stores minimum value
X = min(X, (b - a) / 2);
}
}
}
// Return if X * X if X is not equal
// to 1e9 else return -1
if (X != 1e9)
ans = X * X;
else
ans = -1;
return ans;
}
// Driver code
int main()
{
long N = 3;
cout << SmallestPerfectSquare(N);
return 0;
}
// This code is contributed by AnkitRai01
Java
// Java code to find out the smallest
// perfect square X which when added to N
// yields another perfect square number.
public class GFG {
static long SmallestPerfectSquare(long N)
{
// X is the smallest perfect
// square number
long X = (long)1e9;
long ans;
// Loop from 1 to square root of N
for(int i = 1; i < Math.sqrt(N); i++){
// Condition to check whether i
// is factor of N or not
if (N % i == 0){
long a = i ;
long b = N / i;
// Condition to check whether
// factors satisfies the
// equation or not
if ((b - a != 0) && ((b - a) % 2 == 0)){
// Stores minimum value
X = Math.min(X, (b - a) / 2) ;
}
}
}
// Return if X * X if X is not equal
// to 1e9 else return -1
if (X != 1e9)
ans = X * X;
else
ans = -1;
return ans;
}
// Driver code
public static void main (String[] args){
long N = 3;
System.out.println(SmallestPerfectSquare(N)) ;
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 code to find out the smallest
# perfect square X which when added to N
# yields another perfect square number.
import math
def SmallestPerfectSquare(N):
# X is the smallest perfect
# square number
X = 1e9
# Loop from 1 to square root of N
for i in range(1, int(math.sqrt(N)) + 1):
# Condition to check whether i
# is factor of N or not
if N % i == 0:
a = i
b = N // i
# Condition to check whether
# factors satisfies the
# equation or not
if b - a != 0 and (b - a) % 2 == 0:
# Stores minimum value
X = min(X, (b - a) // 2)
# Return if X * X if X is not equal
# to 1e9 else return -1
return(X * X if X != 1e9 else -1)
# Driver code
if __name__ == "__main__" :
N = 3
print(SmallestPerfectSquare(N))
C#
// C# code to find out the smallest
// perfect square X which when added to N
// yields another perfect square number.
using System;
class GFG {
static long SmallestPerfectSquare(long N)
{
// X is the smallest perfect
// square number
long X = (long)1e9;
long ans;
// Loop from 1 to square root of N
for(int i = 1; i < Math.Sqrt(N); i++){
// Condition to check whether i
// is factor of N or not
if (N % i == 0)
{
long a = i;
long b = N / i;
// Condition to check whether
// factors satisfies the
// equation or not
if ((b - a != 0) && ((b - a) % 2 == 0))
{
// Stores minimum value
X = Math.Min(X, (b - a) / 2);
}
}
}
// Return if X*X if X is not equal
// to 1e9 else return -1
if (X != 1e9)
ans = X * X;
else
ans = -1;
return ans;
}
// Driver code
public static void Main (string[] args)
{
long N = 3;
Console.WriteLine(SmallestPerfectSquare(N));
}
}
// This code is contributed by AnkitRai01
JavaScript
<script>
// JavaScript code to find out the smallest
// perfect square X which when added to N
// yields another perfect square number.
function SmallestPerfectSquare(N){
// X is the smallest perfect
// square number
let X = 1e9;
let ans;
// Loop from 1 to square root of N
for(let i = 1; i < Math.sqrt(N); i++)
{
// Condition to check whether i
// is factor of N or not
if (N % i == 0)
{
let a = i;
let b = N / i;
// Condition to check whether
// factors satisfies the
// equation or not
if((b - a != 0) && ((b - a) % 2 == 0))
{
// Stores minimum value
X = Math.min(X, (b - a) / 2);
}
}
}
// Return if X * X if X is not equal
// to 1e9 else return -1
if (X != 1e9)
ans = X * X;
else
ans = -1;
return ans;
}
// Driver code
let N = 3;
document.write(SmallestPerfectSquare(N));
// This code is contributed by Surbhi Tyagi.
</script>
Time complexity: O(sqrt(N)), since the loop runs from 0 to the square root of N the algorithm takes Sqrt(N) time to run efficiently
Auxiliary Space: O(1), since no extra array is used it takes up constant extra space
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read