Surd number
Last Updated :
24 Aug, 2022
A number is said to be Surd if its square root, cube root, etc are not integers. For example, 9 is not a Surd as square root of 9 is 3, but 5 is Surd as square root of 5 is not integer. Similarly 8 is not a Surd (Cube root of 8 is integer), but 7 is.
Given a range, find if it is Surds or not
Examples:
Input : 4
Output : No
4 is not a Surd number as its square root is
an integer.
Input : 5
Output : Yes
5 is a Surd number as its square root is not an integer.
Input : 8
Output : No
8 is not a Surd number as cube root of 8
is an integer.
The idea is to try every power of all numbers from 2 to ?n and check if any power is equal n or not.
C++
#include <bits/stdc++.h>
using namespace std;
bool isSurd( int n)
{
for ( int i=2; i*i<=n; i++)
{
int j = i;
while (j < n)
j = j * i;
if (j == n)
return false ;
}
return true ;
}
int main()
{
int n = 15;
if (isSurd(n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
class GFG
{
static boolean isSurd( int n)
{
for ( int i = 2 ;
i * i <= n; i++)
{
int j = i;
while (j < n)
j = j * i;
if (j == n)
return false ;
}
return true ;
}
public static void main(String args[])
{
int n = 15 ;
if (isSurd(n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def isSurd(n) :
i = 2
for i in range ( 2 , (i * i) + 1 ) :
j = i
while (j < n) :
j = j * i
if (j = = n) :
return False
return True
if __name__ = = "__main__" :
n = 15
if (isSurd(n)) :
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool isSurd( int n)
{
for ( int i = 2;
i * i <= n; i++)
{
int j = i;
while (j < n)
j = j * i;
if (j == n)
return false ;
}
return true ;
}
public static void Main()
{
int n = 15;
if (isSurd(n))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
PHP
<?php
function isSurd( $n )
{
for ( $i = 2;
$i * $i <= $n ; $i ++)
{
$j = $i ;
while ( $j < $n )
$j = $j * $i ;
if ( $j == $n )
return false;
}
return true;
}
$n = 15;
if (isSurd( $n ))
echo ( "Yes" );
else
echo ( "No" );
?>
|
Javascript
<script>
function isSurd(n)
{
for (let i = 2;
i * i <= n; i++)
{
let j = i;
while (j < n)
j = j * i;
if (j == n)
return false ;
}
return true ;
}
let n = 15;
if (isSurd(n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(?n) as the while loop runs for constant time.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...