📌  相关文章
📜  查找给定数字是否存在于无限序列中

📅  最后修改于: 2021-04-27 20:23:26             🧑  作者: Mango

给定三个整数ABC。在无限序列中, A是第一个数字C公共差(S i – S i – 1 = C)。任务是检查数字B是否会出现在序列中。

例子:

方法:有两种情况:

  1. C = 0时,如果A = B ,则打印“是” ,否则为“否”,因为该序列仅包含数字A
  2. C> 0时,对于任何非负整数k ,必须满足方程B = A + k * C,(B – A)/ C必须为非负整数。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function that returns true if
// the sequence will contain B
bool doesContainB(int a, int b, int c)
{
    if (a == b)
        return true;
  
    if ((b - a) * c > 0 && (b - a) % c == 0)
        return true;
  
    return false;
}
  
// Driver code
int main()
{
    int a = 1, b = 7, c = 3;
  
    if (doesContainB(a, b, c))
        cout << "Yes";
    else
        cout << "No";
  
    return 0;
}


Java
// Java implementation of the approach
class GFG 
{
  
    // Function that returns true if 
    // the sequence will contain B 
    static boolean doesContainB(int a, int b, int c) 
    {
        if (a == b) 
        {
            return true;
        }
  
        if ((b - a) * c > 0 && (b - a) % c == 0) 
        {
            return true;
        }
  
        return false;
    }
  
    // Driver code 
    public static void main(String[] args) 
    {
        int a = 1, b = 7, c = 3;
  
        if (doesContainB(a, b, c)) 
        {
            System.out.println("Yes");
        } 
        else 
        {
            System.out.println("No");
        }
    }
}
  
// This code contributed by Rajput-Ji


Python3
# Python3 implementation of the approach
  
# Function that returns true if
# the sequence will contain B
def doesContainB(a, b, c):
    if (a == b):
        return True
  
    if ((b - a) * c > 0 and (b - a) % c == 0):
        return True
  
    return False
  
# Driver code
if __name__ == '__main__':
    a, b, c = 1, 7, 3
  
    if (doesContainB(a, b, c)):
        print("Yes")
    else:
        print("No")
  
# This code is contributed by 29AjayKumar


C#
// C# implementation of the approach
using System;
  
class GFG 
{
  
    // Function that returns true if 
    // the sequence will contain B 
    static bool doesContainB(int a, int b, int c) 
    {
        if (a == b) 
        {
            return true;
        }
  
        if ((b - a) * c > 0 && (b - a) % c == 0) 
        {
            return true;
        }
  
        return false;
    }
  
    // Driver code 
    public static void Main() 
    {
        int a = 1, b = 7, c = 3;
  
        if (doesContainB(a, b, c)) 
        {
            Console.WriteLine("Yes");
        } 
        else
        {
            Console.WriteLine("No");
        }
    }
}
  
/* This code contributed by PrinciRaj1992 */


PHP
 0 && 
        ($b - $a) % $c == 0)
        return true;
  
    return false;
}
  
// Driver code
$a = 1; $b = 7; $c = 3;
  
if (doesContainB($a, $b, $c))
    echo "Yes";
else
    echo "No";
  
// This code is contributed
// by Akanksha Rai
?>


输出:
Yes