📌  相关文章
📜  检查是否可以通过给定的操作同时使x和y为零

📅  最后修改于: 2021-05-06 20:11:28             🧑  作者: Mango

给定两个数字XY。任务是检查任意多次执行以下操作,是否可以同时将XY减小为零:

  • 选择任何自然数(例如z ),在每次操作中将X和Y减少为以下值之一:
    1. X = X – z和Y = Y – 2 * z
    2. X = X – 2 * z和Y = Y – z

例子:

方法:
以下是给定问题陈述的观察结果:

  1. 由于XY更新为( X – zY – 2 * z )或( X – 2 * zY – z ),因此在n次运算后( X + Y )被更新为( X + Y – 3 * n * z )。因此,如果(X + Y)%3等于0,则X和Y可以同时减小为零。
  2. 在每个步骤中, XY之一减小2 * z 。为了同时将X和Y减少为零,必须满足以下条件: max(X,Y)≤2 * min(X,Y)
    例如:

如果以上两个条件满足X和Y的值,则XY可以同时减小为0
下面是上述方法的实现:

C++
// C++ program of the above approach
#include 
using namespace std;
 
// Function to check if it is possible to
// make x and y can become 0 at same time
void canBeReduced(int x, int y)
{
    int maxi = max(x, y);
    int mini = min(x, y);
 
    // Check the given conditions
    if (((x + y) % 3) == 0 && maxi <= 2*mini)
        cout << "YES" << endl;
    else
        cout << "NO" << endl;
}
 
// Driver Code
int main()
{
    int x = 6, y = 9;
 
    // Function Call
    canBeReduced(x, y);
    return 0;
}


Java
// Java program of the above approach
import java.util.*;
 
class GFG{
  
// Function to check if it is possible to
// make x and y can become 0 at same time
static void canBeReduced(int x, int y)
{
    int maxi = Math.max(x, y);
    int mini = Math.min(x, y);
  
    // Check the given conditions
    if (((x + y) % 3) == 0 && maxi <= 2*mini)
        System.out.print("YES" +"\n");
    else
        System.out.print("NO" +"\n");
}
  
// Driver Code
public static void main(String[] args)
{
    int x = 6, y = 9;
  
    // Function Call
    canBeReduced(x, y);
}
}
 
// This code is contributed by Rajput-Ji


C#
// C# program of the above approach
using System;
 
class GFG 
{
    // Function to check if it is possible to
    // make x and y can become 0 at same time
    static void canBeReduced(int x, int y)
    {
        int maxi = Math.Max(x, y);
        int mini = Math.Min(x, y);
     
        // Check the given conditions
        if (((x + y) % 3) == 0 && maxi <= 2*mini)
            Console.WriteLine("YES");
        else
            Console.WriteLine("NO");
    }
     
    // Driver Code
    static void Main()
    {
        int x = 6, y = 9;
     
        // Function Call
        canBeReduced(x, y);
    }
}
 
// This code is contributed by shubhamsingh10


Python3
# Python 3 program of the above approach
 
# Function to check if it is possible to
# make x and y can become 0 at same time
def canBeReduced(x,y):
    maxi = max(x, y)
    mini = min(x, y)
 
    # Check the given conditions
    if (((x + y) % 3) == 0 and maxi <= 2*mini):
        print("YES")
    else:
        print("NO")
 
# Driver Code
if __name__ == '__main__':
    x = 6
    y = 9
 
    # Function Call
    canBeReduced(x, y)
     
# This code is contributed by Surendra_Gangwar


Javascript


输出:
YES

时间复杂度: O(1)