📌  相关文章
📜  通过从中减去 D 或 1,检查 X 是否可以在精确的 T 次移动中减少到 0

📅  最后修改于: 2021-10-26 05:51:29             🧑  作者: Mango

给定一个整数XDT ,任务是检查是否有可能在 T 次移动中将 X 减少到 0。在每次移动中,X 可以减少 D 或 1。如果可能,打印 YES,否则打印 NO。

例子:

朴素的方法:检查减少 D 和 1 的可能移动,并检查是否可以在 T 移动中使 X 变为 0。
时间复杂度: O(X)

有效的方法:给定的问题可以使用以下步骤解决:

  • KX减少D 的次数
  • 所以总距离将是K*(D) + (T – K) ,它应该等于X
    因此方程变为
  • 对于存在的有效答案,( XT ) 应该可以被 ( D – 1 ) 整除

下面是上述方法的实现:

C++
// C++ Program to implement the above approach
#include 
using namespace std;
 
// Function to check the above problem condition
int possibleReachingSequence(int X, int D, int T)
{
    // Check for base cases
    if (X < T) {
        cout << "NO";
        return 0;
    }
    if (T * D < X) {
        cout << "NO";
        return 0;
    }
    // Check if D - 1 is a divisor of X - T
    if ((X - T) % (D - 1) == 0) {
        cout << "YES";
    }
    else {
        cout << "NO";
    }
    return 0;
}
 
// Driver Code
int main()
{
    int X = 10, D = 3, T = 6;
    possibleReachingSequence(X, D, T);
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to check the above problem condition
static int possibleReachingSequence(int X, int D, int T)
{
    // Check for base cases
    if (X < T) {
        System.out.println("NO");
        return 0;
    }
    if (T * D < X) {
        System.out.println("NO");
        return 0;
    }
    // Check if D - 1 is a divisor of X - T
    if ((X - T) % (D - 1) == 0) {
        System.out.println("YES");
    }
    else {
        System.out.println("NO");
    }
    return 0;
}
 
 
// Driver Code
public static void main(String args[])
{
    int X = 10, D = 3, T = 6;
    possibleReachingSequence(X, D, T);
}
}


Python3
# Python program for the above approach
 
# Function to check the above problem condition
def possibleReachingSequence(X, D, T):
   
  # Check the base case.
  if X < T:
    return "NO"
  if T*D < X:
    return "NO"
   
  # check if X-T is a divisor of D-1
  if (X - T) % (D - 1) == 0:
    return "YES"
  return "NO"
 
# Driver code
X = 10
D = 3
T = 6
print(possibleReachingSequence(X, D, T))
 
# This code is contributed by maddler.


C#
// C# program for the above approach
 
using System;
 
public class GFG{
 
// Function to check the above problem condition
static int possibleReachingSequence(int X, int D, int T)
{
    // Check for base cases
    if (X < T) {
        Console.WriteLine("NO");
        return 0;
    }
    if (T * D < X) {
        Console.WriteLine("NO");
        return 0;
    }
    // Check if D - 1 is a divisor of X - T
    if ((X - T) % (D - 1) == 0) {
        Console.WriteLine("YES");
    }
    else {
        Console.WriteLine("NO");
    }
    return 0;
}
 
 
// Driver Code
public static void Main(string []args)
{
    int X = 10, D = 3, T = 6;
    possibleReachingSequence(X, D, T);
}
}
 
// This code is contributed by AnkThon


输出
YES

时间复杂度: O(1)
辅助空间: O(1)