📜  满足给定方程的一对整数(a,b)

📅  最后修改于: 2021-04-24 03:50:33             🧑  作者: Mango

给定方程组a 2 + b = na + b 2 = m 。任务是找到满足给定nm方程的正整数对(a,b)的数量。
例子:

方法:
该方法是检查所有可能的数字对,并检查该对是否满足两个方程式。为此,我们有

a2 + b = n ... (1)
   a + b2 = m ... (2)
For equation (2), 
=> a = m - b2 ... (3)
  • 现在,对于a的正值,b的每个值都必须从0到sqrt(m)。
  • 从等式(3)获得a的值。
  • 如果对(a,b)满足方程式(1),则对(a,b)是方程组的解。

下面是上述方法的实现:

C++
// C++ program to count the pair of integers(a, b)
// which satisfy the equation
// a^2 + b = n and a + b^2 = m
#include 
using namespace std;
 
// Function to count valid pairs
int pairCount(int n, int m)
{
    int cnt = 0, b, a;
    for (b = 0; b <= sqrt(m); b++) {
        a = m - b * b;
        if (a * a + b == n) {
            cnt++;
        }
    }
    return cnt;
}
 
// Driver code
int main()
{
    int n = 9, m = 3;
 
    cout << pairCount(n, m) << endl;
 
    return 0;
}


Java
// Java program to count the pair of integers(a, b)
// which satisfy the equation
// a^2 + b = n and a + b^2 = m
class GFG
{
 
// Function to count valid pairs
static int pairCount(int n, int m)
{
    int cnt = 0, b, a;
    for (b = 0; b <= Math.sqrt(m); b++)
    {
        a = m - b * b;
        if (a * a + b == n)
        {
            cnt++;
        }
    }
    return cnt;
}
 
// Driver code
public static void main(String[] args)
{
    int n = 9, m = 3;
    System.out.print(pairCount(n, m) +"\n");
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program to count the pair of integers(a, b)
# which satisfy the equation
# a^2 + b = n and a + b^2 = m
 
# Function to count valid pairs
def pairCount(n, m):
    cnt = 0;
    for b in range(int(pow(m, 1/2))):
        a = m - b * b;
        if (a * a + b == n):
            cnt += 1;
         
    return cnt;
 
# Driver code
if __name__ == '__main__':
    n = 9;
    m = 3;
    print(pairCount(n, m));
     
# This code is contributed by 29AjayKumar


C#
// C# program to count the pair of integers(a, b)
// which satisfy the equation
// a^2 + b = n and a + b^2 = m
using System;
 
class GFG
{
 
// Function to count valid pairs
static int pairCount(int n, int m)
{
    int cnt = 0, b, a;
    for (b = 0; b <= Math.Sqrt(m); b++)
    {
        a = m - b * b;
        if (a * a + b == n)
        {
            cnt++;
        }
    }
    return cnt;
}
 
// Driver code
public static void Main(String[] args)
{
    int n = 9, m = 3;
    Console.Write(pairCount(n, m) +"\n");
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
1

时间复杂度: O(sqrt(min(n,m))