Maximize value of (a+b) such that (a*a-b*b = N)
Last Updated :
20 Dec, 2022
Given an odd value N, the task is to find the maximized value of (a+b) ( where a and b are integers ) such that (a2 – b2 = N)
Examples:
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.
Approach:
a*a - b*b = N
=> (a+b)*(a-b) = N
=> (a+b) = N/(a-b)
- Now for the above equation to be true
We know that
|a - b| ? 1
Therefore,
a + b ? N
- Now inorder to maximise the value of (a + b),
Maximising a + b ? N
=> a + b = N
- Hence, N is the maximum value of (a + b) when we need to maximize the value of (a+b) such that (a*a-b*b = N).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxValue( int n)
{
return n;
}
int main()
{
int n = 1;
cout << maxValue(n);
return 0;
}
|
Java
class GFG
{
static int maxValue( int n)
{
return n;
}
public static void main(String[] args)
{
int n = 1 ;
System.out.print(maxValue(n));
}
}
|
Python3
def maxValue(n) :
return n;
if __name__ = = "__main__" :
n = 1 ;
print (maxValue(n));
|
C#
using System;
class GFG
{
static int maxValue( int n)
{
return n;
}
public static void Main(String[] args)
{
int n = 1;
Console.Write(maxValue(n));
}
}
|
Javascript
<script>
function maxValue(n)
{
return n;
}
var n = 1;
document.write(maxValue(n));
</script>
|
Time Complexity:
Auxiliary Space: O(1)
As constant extra space is used.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...