查找数字是否是AP的一部分,其第一个元素和不同之处是使用C ++给出的。

假设我们拥有AP的第一个元素,并且有所不同。我们必须检查给定的数字n是否是AP的一部分。如果第一项是a = 1,差分= 3,则将检查项x = 7。答案是肯定的。

为了解决这个问题,我们将按照以下步骤操作:

  • 如果d为0,且a = x,则返回true,否则返回false。

  • 否则,如果d不为0,则x属于序列x = a + n * d,其中n是一个非负整数,只有(n-a)/ c是一个非负整数。

示例

#include <iostream>
using namespace std;
bool isInAP(int a, int d, int x) {
   if (d == 0)
   return (x == a);
   return ((x - a) % d == 0 && (x - a) / d >= 0);
}
int main() {
   int a = 1, x = 7, d = 3;
   if (isInAP(a, d, x))
      cout << "The value " << x << " is present in the AP";
   else
      cout << "The value " << x << "is not present in the AP";
}

输出结果

The value 7 is present in the AP