使用对数函数查找两个数字之间的差异
给定两个整数a和b ,任务是使用 log函数找到a和b的减法,即(ab) 。
Note: We can not use the – operator.
例子:
Input: a = 4, b = 81
Output: -77
Input: a = -3, b = 16
Output: -19
Input: a = -3, b = -13
Output: 10
方法:写这个问题的解决方案,使用日志的以下三个属性
- log( a / b) = log( a ) – log( b )
- log a( a ) = 1
- log ( ab ) = b log ( a )
结合这三个属性并编写。
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
请按照以下步骤解决问题:
- ab的减法将是log(exp(a) / exp(b))作为答案。
下面是上述方法的实现。
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the subtraction
// of two number a and b i.e, (a-b)
int subtract(int a, int b)
{
return log(exp(a) / exp(b));
}
// Driver Code
int main()
{
int a = -15;
int b = 7;
cout << subtract(a, b);
return 0;
}
Java
// Java program for the above approach
class GFG {
// Function to find the subtraction
// of two number a and b i.e, (a-b)
static int subtract(int a, int b) {
return (int) Math.log(Math.exp(a) / Math.exp(b));
}
// Driver Code
public static void main(String[] args) {
int a = -15;
int b = 7;
System.out.print(subtract(a, b));
}
}
// This code is contributed by shikhasingrajput
Python3
# Python3 program for the above approach
import math
# Function to find the subtraction
# of two number a and b i.e, (a-b)
def subtract(a, b) :
return math.log(math.exp(a) / math.exp(b));
# Driver Code
if __name__ == "__main__" :
a = -15;
b = 7;
print(subtract(a, b));
# This code is contributed by AnkThon
C#
// C# program for the above approach
using System;
public class GFG {
// Function to find the subtraction
// of two number a and b i.e, (a-b)
static int subtract(int a, int b)
{
return (int)Math.Log(Math.Exp(a) / Math.Exp(b));
}
// Driver Code
public static void Main(string[] args) {
int a = -15;
int b = 7;
Console.Write(subtract(a, b));
}
}
// This code is contributed by AnkThon
Javascript
输出
-22
时间复杂度: O(1)
辅助空间: O(1)