Check if the square of a number is divisible by K or not
Last Updated :
12 Nov, 2021
Given two integers, X and K, the task is to find if X2 is divisible by K or not. Here, both K and X can lie in the range [1,1018].
Examples:
Input: X = 6, K = 9
Output: YES
Explanation:
Since 62 is equal to 36, which is divisible by 9.
Input: X = 7, K = 21
Output: NO
Explanation:
Since 72 is equal to 49, which is not divisible by 21.
Approach:
As mentioned above, X can lie in the range [1,1018], so we can not directly check if X2 is divisible by K or not as it can cause a memory overflow. Hence the efficient approach is to first calculate the Greatest Common Divisor of X and K. After the GCD is calculated, we will take it as the maximum portion which we can divide from X and K. Reduce K by GCD and check if X is divisible by the reduced K or not.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void checkDivisible( int x, int k)
{
int g = __gcd(x, k);
k /= g;
if (x % k == 0) {
cout << "YES\n" ;
}
else {
cout << "NO\n" ;
}
}
int main()
{
int x = 6, k = 9;
checkDivisible(x, k);
return 0;
}
|
Java
class GFG{
static void checkDivisible( int x, int k)
{
int g = __gcd(x, k);
k /= g;
if (x % k == 0 )
{
System.out.print( "YES\n" );
}
else
{
System.out.print( "NO\n" );
}
}
static int __gcd( int a, int b)
{
return b == 0 ? a : __gcd(b, a % b);
}
public static void main(String[] args)
{
int x = 6 , k = 9 ;
checkDivisible(x, k);
}
}
|
Python3
from math import gcd
def checkDivisible(x, k):
g = gcd(x, k)
k / / = g
if (x % k = = 0 ):
print ( "YES" )
else :
print ( "NO" )
if __name__ = = '__main__' :
x = 6
k = 9
checkDivisible(x, k);
|
C#
using System;
class GFG{
static void checkDivisible( int x, int k)
{
int g = __gcd(x, k);
k /= g;
if (x % k == 0)
{
Console.Write( "YES\n" );
}
else
{
Console.Write( "NO\n" );
}
}
static int __gcd( int a, int b)
{
return b == 0 ? a : __gcd(b, a % b);
}
public static void Main(String[] args)
{
int x = 6, k = 9;
checkDivisible(x, k);
}
}
|
Javascript
<script>
function gcd(a, b)
{
return b == 0 ? a : gcd(b, a % b);
}
function checkDivisible(x, k)
{
var g = gcd(x, k);
k /= g;
if (x % k == 0)
{
document.write( "YES" );
}
else
{
document.write( "NO" );
}
}
var x = 6, k = 9;
checkDivisible(x, k);
</script>
|
Time Complexity: O(log(max(x, k)))
Auxiliary Space;:O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...