Smallest and Largest N-digit perfect squares
Given an integer N, the task is to find the smallest and the largest N digit numbers which are also perfect squares.
Examples:
Input: N = 2
Output: 16 81
16 and 18 are the smallest and the largest 2-digit perfect squares.
Input: N = 3
Output: 100 961
Approach: For increasing values of N starting from N = 1, the series will go on like 9, 81, 961, 9801, ….. for the largest N-digit perfect square whose Nth term will be pow(ceil(sqrt(pow(10, N))) – 1, 2).
And 1, 16, 100, 1024, ….. for the smallest N-digit perfect square whose Nth term will be pow(ceil(sqrt(pow(10, N – 1))), 2).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void nDigitPerfectSquares( int n)
{
cout << pow ( ceil ( sqrt ( pow (10, n - 1))), 2) << " " ;
cout << pow ( ceil ( sqrt ( pow (10, n))) - 1, 2);
}
int main()
{
int n = 4;
nDigitPerfectSquares(n);
return 0;
}
|
Java
class GFG {
static void nDigitPerfectSquares( int n)
{
int smallest = ( int )Math.pow(Math.ceil(Math.sqrt(Math.pow( 10 , n - 1 ))), 2 );
System.out.print(smallest + " " );
int largest = ( int )Math.pow(Math.ceil(Math.sqrt(Math.pow( 10 , n))) - 1 , 2 );
System.out.print(largest);
}
public static void main(String args[])
{
int n = 4 ;
nDigitPerfectSquares(n);
}
}
|
Python3
import math
def nDigitPerfectSquares(n):
print ( pow (math.ceil(math.sqrt( pow ( 10 , n - 1 ))), 2 ),
end = " " );
print ( pow (math.ceil(math.sqrt( pow ( 10 , n))) - 1 , 2 ));
n = 4 ;
nDigitPerfectSquares(n);
|
C#
using System;
public class GFG {
static void nDigitPerfectSquares( int n)
{
int smallest = ( int )Math.Pow(Math.Ceiling(Math.Sqrt(Math.Pow(10, n - 1))), 2);
Console.Write(smallest + " " );
int largest = ( int )Math.Pow(Math.Ceiling(Math.Sqrt(Math.Pow(10, n))) - 1, 2);
Console.Write(largest);
}
public static void Main(String []args)
{
int n = 4;
nDigitPerfectSquares(n);
}
}
|
PHP
<?php
function nDigitPerfectSquares( $n )
{
echo pow( ceil (sqrt(pow(10, $n - 1))), 2), " " ;
echo pow( ceil (sqrt(pow(10, $n ))) - 1, 2);
}
$n = 4;
nDigitPerfectSquares( $n );
?>
|
Javascript
<script>
function nDigitPerfectSquares(n)
{
document.write(Math.pow(Math.ceil(Math.sqrt(Math.pow(10, n - 1))), 2) + " " );
document.write(Math.pow(Math.ceil(Math.sqrt(Math.pow(10, n))) - 1, 2));
}
var n = 4;
nDigitPerfectSquares(n);
</script>
|
Auxiliary Space: O(1)
Last Updated :
15 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...