Find the difference between two numbers using log function
Last Updated :
25 Nov, 2021
Given two integers a and b, the task is to find the subtraction of a and b i.e, (a-b) using the log function.
Note: We can not use the – operator.
Examples:
Input: a = 4, b = 81
Output: -77
Input: a = -3, b = 16
Output: -19
Input: a = -3, b = -13
Output: 10
Approach: To write the solution to this question, use the following three properties of the log
- log( a / b) = log( a ) – log( b )
- log a( a ) = 1
- log ( ab ) = b log ( a )
Combine these three properties and write.
loge ( ea / eb )
=> loge ( ea ) – loge ( eb ) {using property 1}
= > a loge ( e ) – bloge ( e ) {using property 2}
= > a – b {using property 3}
Note: e is the Euler number i.e, 2.71828
Follow the steps below to solve the problem:
- The subtraction of a-b will be log(exp(a) / exp(b)) as the answer.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int subtract( int a, int b)
{
return log ( exp (a) / exp (b));
}
int main()
{
int a = -15;
int b = 7;
cout << subtract(a, b);
return 0;
}
|
Java
class GFG {
static int subtract( int a, int b) {
return ( int ) Math.log(Math.exp(a) / Math.exp(b));
}
public static void main(String[] args) {
int a = - 15 ;
int b = 7 ;
System.out.print(subtract(a, b));
}
}
|
Python3
import math
def subtract(a, b) :
return math.log(math.exp(a) / math.exp(b));
if __name__ = = "__main__" :
a = - 15 ;
b = 7 ;
print (subtract(a, b));
|
C#
using System;
public class GFG {
static int subtract( int a, int b)
{
return ( int )Math.Log(Math.Exp(a) / Math.Exp(b));
}
public static void Main( string [] args) {
int a = -15;
int b = 7;
Console.Write(subtract(a, b));
}
}
|
Javascript
<script>
function subtract(a, b) {
return Math.log(Math.exp(a) / Math.exp(b));
}
let a = -15;
let b = 7;
document.write(subtract(a, b));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...