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:
- Given
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++
// C++ program to maximize the value // of (a+b) such that (a*a-b*b = N) #include <bits/stdc++.h> 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
<script> // Javascript 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) function maxValue(n) { return n; } // Driver code var n = 1; document.write(maxValue(n)); </script> |
1
Time Complexity:
Auxiliary Space: O(1)
As constant extra space is used.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!