Check whether the number formed by concatenating two numbers is a perfect square or not
Given two numbers a and b and the task is to check whether the concatenation of a and b is a perfect square or not.
Examples:
Input: a = 1, b = 21
Output: Yes
121 = 11 × 11, is a perfect square.
Input: a = 100, b = 100
Output: No
100100 is not a perfect square.
Approach: Initialize the number as strings initially and concatenate them. Convert the string to a number using Integer.valueOf() function. Once the string has been converted to a number, check if the number is a perfect square or not.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
void checkSquare(string s1, string s2)
{
int c = stoi(s1 + s2);
int d = sqrt (c);
if (d * d == c)
{
cout << "Yes" ;
}
else
{
cout << "No" ;
}
}
int main()
{
string s1 = "12" ;
string s2 = "1" ;
checkSquare(s1, s2);
return 0;
}
|
Java
import java.lang.*;
class GFG {
static void checkSquare(String s1, String s2)
{
int c = Integer.valueOf(s1 + s2);
int d = ( int )Math.sqrt(c);
if (d * d == c) {
System.out.println( "Yes" );
}
else {
System.out.println( "No" );
}
}
public static void main(String[] args)
{
String s1 = "12" ;
String s2 = "1" ;
checkSquare(s1, s2);
}
}
|
Python 3
import math
def checkSquare(s1, s2):
c = int (s1 + s2)
d = math.sqrt(c)
if (d * d = = c) :
print ( "Yes" )
else :
print ( "No" )
if __name__ = = "__main__" :
s1 = "12"
s2 = "1"
checkSquare(s1, s2)
|
C#
using System;
public class GFG {
static void checkSquare(String s1, String s2)
{
int c = Convert.ToInt32(s1 + s2 );
int d = ( int )Math.Sqrt(c);
if (d * d == c) {
Console.WriteLine( "Yes" );
}
else {
Console.WriteLine( "No" );
}
}
public static void Main()
{
String s1 = "12" ;
String s2 = "1" ;
checkSquare(s1, s2);
}
}
|
PHP
<?php
function checkSquare( $s1 , $s2 )
{
$c = $s1 . $s2 ;
$d = sqrt( $c );
if ( $d * $d == $c )
{
echo "Yes" ;
}
else
{
echo "No" ;
}
}
$s1 = "12" ;
$s2 = "1" ;
checkSquare( $s1 , $s2 );
?>
|
Javascript
<script>
function checkSquare(s1,s2)
{
let c = parseInt(s1 + s2);
let d = Math.floor(Math.sqrt(c));
if (d * d == c) {
document.write( "Yes" );
}
else {
document.write( "No" );
}
}
let s1 = "12" ;
let s2 = "1" ;
checkSquare(s1, s2);
</script>
|
Time complexity: log(c) as using inbuilt sqrt function
Auxiliary space: O(1)
Last Updated :
13 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...