Open In App

Maximize value of (a+b) such that (a*a-b*b = N)

Last Updated : 20 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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>

                    

Output: 
1

 

Time Complexity: O(1)
Auxiliary Space: O(1)

As constant extra space is used.
 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads