Nearest Perfect Square | Practice | GeeksforGeeks

Given a number N. Find out the nearest number which is a perfect square and also the absolute difference between them.
Example 1:
Input:
N = 25
Output:
25 0
Explanation:
Since 25 is a perfect square, it is the 
closest perfect square to itself and 
absolute difference is 25-25=0.
Example 2:
Input:
N = 1500
Output:
1521 21
Explanation:
Two of the closest perfect squares to 
1521 are 1444.Thus, 1521 is the closest 
perfect square to 1500 and the absolute 
difference  between them is 1521-1500=21.

Your Task:
You don't need to read input or print anything.Your Task is to complete the function nearestPerfectSquare() which takes the number N as input parameters and returns the nearest perfect square as well as the absolute difference between them.

Expected Time Complexity:O(sqrt(N))
Expected Space Auxillary:O(1)

Constraints:
1<=N<=109
0
60mqcs20shivamyadav17 hours ago
#Python solution
#code here(return list of two numbers)       b = int(math.sqrt(N))       s1 = b **2       s2 = (b+1) **2       d1 = N - s1       d2 = s2 - N       if d1<d2:           return s1,d1       return s2,d2
0
shikhardubey94577568753 weeks ago
SIMPLE FOR THE C++;
// { Driver Code Starts// Initial Template for C++
#include <bits/stdc++.h>using namespace std;
// } Driver Code Ends// User function template for C++
class Solution { public:   vector<int> nearestPerfectSquare(int N) {       vector < int > ans ;       long long int  fl = floor ( sqrt(N));       long long int  ce = ceil ( sqrt (N));       long long int  ans1 = fl * fl ;       long long int ans2 = ce*ce;       if ( ans2 - N < N- ans1)       {           ans.push_back(ans2);           ans.push_back( ans2 - N);       }else{           ans.push_back(ans1);           ans.push_back(N-ans1);       }       return ans ;   }};
// { Driver Code Starts.int main() {   int t;   cin >> t;   while (t--) {       int N;       cin >> N;       Solution ob;       vector<int> ans = ob.nearestPerfectSquare(N);       cout << ans[0] << " " << ans[1] << "\n";   }}  // } Driver Code Ends
+1
mashhadihossain3 weeks ago
SIMPLE JAVA SOLUTION (2.41/5.33 SEC)
class Solution {   int[] nearestPerfectSquare(int N) {       double val=Math.sqrt(N);       int value=(int)val;       int ans[]=new int[2];       if(value==val)       {           ans[0]=N;           ans[1]=0;       }       else if(val>value)       {           int extra=value+1;           int one=value*value;           int two=extra*extra;           if(Math.abs(N-one)<Math.abs(N-two))           {               ans[0]=one;               ans[1]=Math.abs(N-one);           }           else           {               ans[0]=two;               ans[1]=Math.abs(N-two);           }       }       return ans;   }}
0
ajaybchaudhari213 months ago
Java Solution using binary search to find the sqrt and then checking if next square is closet or not....
 
class Solution {
    int[] nearestPerfectSquare(int sq) {
    
        long sqrt = findSquare(sq);
        
        long lower = 0;
        long upper = 0;
        
        int[] arr = new int[2];
        
        if((sqrt*sqrt) == sq){
            arr[0] = (int)(sqrt*sqrt);
            arr[1] = 0;
            return arr;
        }else{
            lower = sqrt;
            upper = sqrt+1;
        }
        
        //System.out.println(lower+" "+sqrt+" "+upper);
        
        int ans = (int)(Math.abs(sq-lower*lower) < Math.abs(sq-upper*upper) ? lower*lower : upper*upper);
        arr[0] = ans;
        if(ans == lower*lower){
            arr[1] = (int)(sq - lower*lower);
        }else{
            arr[1] = (int)(upper*upper - sq);
        }
	    
	    return arr;
    
        
    }
    
    public long findSquare(int sq){
	    long start = 0;
	    long end = sq;
	    long sqrt = -1;

        while(start <= end){
            long mid = (start+end)/2;
            if(mid*mid == sq){
                return mid;
            }else if(mid*mid > sq){
                end = mid -1;
            }else{
                start = mid+1;
                sqrt = mid;
            }
        }
        
        return sqrt;
	}
}
0
kumarsatyam74249050564 months ago
can any one please tell why is my code not runing                                  class Solution {   int[] nearestPerfectSquare(int n) {       long i=0; long res=0,m=0; while(i*i<n) i++;long c=Math.abs(n-(i*i));long d=Math.abs(n-((i-1)*(i-1)));if(c>d){  res=(i-1)*(i-1);  m=d;}else if(c<d){   res=(i)*(i);  m=c;}else if(c==d){    if((i*i)>((i-1)*(i-1)))   { res=i*i;    m=c;}    else    {        res=(i-1)*(i-1);        m=c;    }}int a[]=new int[2];a[0]=(int)res;a[1]=(int)m;return a;   }}
0
aniketsingh27220016 months ago
class Solution { public:   vector<int> nearestPerfectSquare(int N) {       // code here       int a=sqrt(N);       if(a*a==N)           return {N,0};       long long int b=pow(a+1,2);       long long int c=pow(a,2);       if(b-N<N-c)           return {b,b-N};       else           return {c,N-c};   }};
0
Radhika Gupta9 months ago
Radhika Gupta
CORRECT CPP SOLUTIONhttps://ide.geeksforgeeks.o...
0
Rakshit Pandey1 year ago
Rakshit Pandey
** USING Floor and Ceil **    vector<int> nearestPerfectSquare(int N) {        double f=sqrt(N);        int v1=floor(f);        int v2=ceil(f);        vector<int>v;        v1=v1*v1;        v2=v2*v2;        if((v2-N)>=(N-v1))        {            v.push_back(v1);            v.push_back(N-v1);        }        else        {            v.push_back(v2);            v.push_back(v2-N);        }        return v;        // code here    }
0
deepak sagore1 year ago
deepak sagore
class Solution {    int[] nearestPerfectSquare(int N) {        // code here        int arr[] = new int[2];        double demoSq = Math.sqrt(N);        if(demoSq == (int)demoSq){            arr[0] =(int) (demoSq * demoSq);            arr[1] = 0;            return arr;        }        int sq = (int)demoSq;        int prev = (sq) * (sq);        int next = (sq + 1) * (sq + 1);
        if(Math.abs(N - prev) < Math.abs(N - next)){            arr[0] = prev;            arr[1] = Math.abs(N - prev);            return arr;        }        arr[0] = next;        arr[1] = Math.abs(N - next);        return arr;    }
}
0
Akhila2 years ago
Akhila
class GFG {    static boolean isPerfect(int n)    {        if ((Math.sqrt(n) - Math.floor(Math.sqrt(n))) != 0)             return false;         return true;
    }    public static void main(String args[])    {        Scanner sc=new Scanner(System.in);        int t=sc.nextInt();        for(int i=0;i<t;i++) {="" int="" n="sc.nextInt();" if(isperfect(n))="" {="" system.out.println(n+"="" "+0);="" break;="" }="" int="" n1="n-1;" while(true)="" {="" if(isperfect(n1))="" break;="" n1--;="" }="" int="" n2="n+1;" while(true)="" {="" if(isperfect(n2))="" break;="" n2++;="" }="" int="" d1="n-n1;" int="" d2="n2-n;" if(d1<d2)="" system.out.println(n1+"="" "+d1);="" else="" system.out.println(n2+"="" "+d2);="" }="" }="" }="">
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.