📜  检查数字的平方是否可被K整除

📅  最后修改于: 2021-06-26 15:25:40             🧑  作者: Mango

给定两个整数XK ,任务是确定X 2是否可被K整除。在此, KX都可以在[1,10 18 ]范围内。

例子:

方法:
如上所述, X可以在[1,10 18 ]范围内,因此我们不能直接检查X 2是否可被K整除,因为它会导致内存溢出。因此,有效的方法是首先计算XK的最大公约数。计算完GCD后,我们将其作为可以除以XK的最大部分。用GCD还原K,然后检查X是否可被还原的K整除。

下面是上述方法的实现:

C++
// C++ implementation to
// check if the square of X is
// divisible by K
 
#include 
using namespace std;
 
// Function to return if
// square of X is divisible
// by K
void checkDivisible(int x, int k)
{
    // Finding gcd of x and k
    int g = __gcd(x, k);
 
    // Dividing k by their gcd
    k /= g;
 
    // Check for divisibility of X
    // by reduced K
    if (x % k == 0) {
        cout << "YES\n";
    }
    else {
        cout << "NO\n";
    }
}
 
// Driver Code
int main()
{
    int x = 6, k = 9;
    checkDivisible(x, k);
 
    return 0;
}


Java
// Java implementation to
// check if the square of X is
// divisible by K
 
class GFG{
 
// Function to return if
// square of X is divisible
// by K
static void checkDivisible(int x, int k)
{
    // Finding gcd of x and k
    int g = __gcd(x, k);
 
    // Dividing k by their gcd
    k /= g;
 
    // Check for divisibility of X
    // by reduced K
    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);    
}
 
// Driver Code
public static void main(String[] args)
{
    int x = 6, k = 9;
    checkDivisible(x, k);
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 implementation to
# check if the square of X is
# divisible by K
 
from math import gcd
 
# Function to return if
# square of X is divisible
# by K
def checkDivisible(x, k):
     
    # Finding gcd of x and k
    g = gcd(x, k)
 
    # Dividing k by their gcd
    k //= g
 
    # Check for divisibility of X
    # by reduced K
    if (x % k == 0):
        print("YES")
    else:
        print("NO")
 
# Driver Code
if __name__ == '__main__':
     
    x = 6
    k = 9
    checkDivisible(x, k);
     
# This code is contributed by Bhupendra_Singh


C#
// C# implementation to check
// if the square of X is
// divisible by K
using System;
 
class GFG{
 
// Function to return if
// square of X is divisible
// by K
static void checkDivisible(int x, int k)
{
     
    // Finding gcd of x and k
    int g = __gcd(x, k);
 
    // Dividing k by their gcd
    k /= g;
 
    // Check for divisibility of X
    // by reduced K
    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);    
}
 
// Driver Code
public static void Main(String[] args)
{
    int x = 6, k = 9;
     
    checkDivisible(x, k);
}
}
 
// This code is contributed by Princi Singh


Javascript


输出:
YES

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。