📜  最大化(a + b)的值,使得(a * ab * b = N)

📅  最后修改于: 2021-04-27 05:16:48             🧑  作者: Mango

给定一个奇数值N ,任务是找到(a + b)的最大值(其中ab是整数),使得(a 2 – b 2 = N)
例子:

Input: N = 1
Output: 1
Since a*a - b*b = 1 
The maximum value occurs when a = 1 and b = 0. 
Thus, a + b = 1.

Input: N = 3
Output: 3
Since a*a - b*b = 3 
The maximum value occurs when a = 2 and b = 1. 
Thus, a + b = 3.

方法:

  • 给定
a*a - b*b = N
=> (a+b)*(a-b) = N
=> (a+b) = N/(a-b)
  • 现在上述方程式成立
We know that 
|a - b| ≥ 1

Therefore,
a + b ≤ N
  • 现在为了最大化(a + b)的值,
Maximising a + b ≤ N

=> a + b = N
  • 因此,当我们需要最大化(a + b)的值使得(a * ab * b = N)时,N是(a + b)的最大值。

下面是上述方法的实现:

C++
// C++ program to maximize the value
// of (a+b) such that (a*a-b*b = N)
 
#include 
using namespace std;
 
// Function to maximize the value
// of (a+b) such that (a*a-b*b = n)
int maxValue(int n)
{
    return n;
}
 
// Driver code
int main()
{
    int n = 1;
 
    cout << maxValue(n);
 
    return 0;
}


Java
// Java program to maximize the value
// of (a+b) such that (a*a-b*b = N)
class GFG
{
 
// Function to maximize the value
// of (a+b) such that (a*a-b*b = n)
static int maxValue(int n)
{
    return n;
}
 
// Driver code
public static void main(String[] args)
{
    int n = 1;
 
    System.out.print(maxValue(n));
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program to maximize the value
# of (a+b) such that (a*a-b*b = N)
 
# Function to maximize the value
# of (a+b) such that (a*a-b*b = n)
def maxValue(n) :
 
    return n;
 
# Driver code
if __name__ == "__main__" :
 
    n = 1;
 
    print(maxValue(n));
     
# This code is contributed by AnkitRai01


C#
// C# program to maximize the value
// of (a+b) such that (a*a-b*b = N)
using System;
 
class GFG
{
 
    // Function to maximize the value
    // of (a+b) such that (a*a-b*b = n)
    static int maxValue(int n)
    {
        return n;
    }
     
    // Driver code
    public static void Main(String[] args)
    {
        int n = 1;
     
        Console.Write(maxValue(n));
    }
}
 
// This code is contributed by PrinciRaj1992


Javascript


输出:
1

时间复杂度: O(1)