input : x = 30 y = 2output : 4, 7, 14, 28explanation : 30 mod 4 = 2 (equals y), 30 mod 7 = 2 (equals y), 30 mod 14 = 2 (equals y), 30 mod 28 = 2 (equals y)input : x = 30 y = 2output : 4, 7, 14, 28explanation : 30 mod 4 = 2 (equals y), 30 mod 7 = 2 (equals y), 30 mod 14 = 2 (equals y), 30 mod 28 = 2 (equals y)
正如我们在上面的例子中看到的,每个整数都是除 x 后得到余数 y 的解。在这个例子中,30 除以 4、7、14、28 得到余数 2,等于 y。我们将以这种方式求解模方程。
求解的方法我们可以应用一种简单的方法,将 x 除以从 1 开始的每个整数,并检查它是否给出余数 y,或者我们可以将 (x - y) 除以每个整数,并且除以 (x - y) 但不能除 x 的整数是解。让我们编写一个 c++ 程序来查找模方程的不同解。
示例#include <bits/stdc++.h>using namespace std;int numberofdivisor(int x, int y){ int n = (x - y); int noofdivisors = 1; for (int i = 1; i <= n/2; i++) { // if n is divisible by i if ((n % i) == 0) { // count if integer is greater than y if (i > y) noofdivisors++; } } return noofdivisors;}void numberofsolutions(int x, int y){ int noofsolutions; if (x == y) noofsolutions = -1; if (x < y) noofsolutions = 0; if (x > y) noofsolutions = numberofdivisor(x, y); if (noofsolutions == -1) { cout << "x can take infinitely many values" " greater than " << x << "\n"; } else { cout << "number of solution = " << noofsolutions; }}// main functionint main(){ int x,y; cin >> x; cin >> y; numberofsolutions(x, y); return 0;}
输出当我们写入 0 作为输入时,程序会给出如下输出 -
x can take infinitely many values greater than 0
当我们输入其他数字时,上面的程序会显示这样的输出(这里我们提供了 5 作为输入) -
number of solution = 2
上面代码的解释现在我们对每个函数进行解释,以便您可以轻松理解程序。
main()函数在main中函数中,我们将 x 和 y 的值作为输入,并通过调用 numberofsolutions() 函数查找可能的解决方案的数量。
numberofsolutions()函数该函数检查 x 和 y 是否满足x 应该大于 y 的条件,因为我们找不到大于被除数的余数。此函数调用另一个函数 numberofdivisor() 并获取 x 的除数数,从而得出余数 y。
numberofdivisor() 函数此函数查找 x 的除数数 - y 通过运行从 1 到 (x - y)/2 的循环并检查每个整数是否能整除,并且该整数不应完全整除 x。
结论模方程的解是除 x 并得到余数 y 的整数;我们从各种例子中了解到这一点。方程可以有一些解,因此我们通过应用简单的方法来找到这些解。
我们可以编写一个 c++ 程序来计算模方程的解。我们可以用其他语言(例如 c、java、python 或任何其他编程语言)编写相同的程序。希望您发现本文有助于理解如何找到模方程的多个解的概念。
以上就是使用c++找到模方程的解的数量的详细内容。
