Compare two floating-point numbers given in Scientific Notations
Given two strings N and M in the form of a * 10 b. The task is to compare given two floating-point numbers and print the smaller number and if both the numbers are equal then print Equal.
0<|a|<10^9 and -10^9<b<10^9.
N and M are two numbers with two parts:
- a1 is mantissa of N and a2 is mantissa of M.
- b1 is exponent of N and b2 is exponent of M.
Input: N = 3*10^2, M = 299*10^0
a1 = 3, b1 = 2
a2 = 299, b2 = 0
N = 3*10^2 = 300
M = 299*10^0 = 299.
We know that 299 is smaller than 300.
Input: N = -5*10^3, M = -50*10^2
Output : Equal
a1 = -5, b1 = 3
a2 = -50, b2 = 2
N = -5*10^3 = -5000
M = -50*10^2 = -5000
Hence, N and M are equal.
Input: N = -2*10^1, M = -3*10^1
a1 = -2 , b1 = 1
a2 = -3 , b2 = 1
N = -20
M = -30
-30 is less than -20, hence M is smaller number.
Naive Approach: We will calculate the values of numbers extracted from strings N and M and then compare which one is better. The bigInteger class will be used for storing and calculating the value of N and M in Java. This approach can give Time Limit Exceeded error for larger test cases.
- Extract mantissa and exponents from both the strings N and M.
- Find the index of ‘*’ ( let say mulInd), then substring before mulInd will be mantissa(a1).
- Find the index of ‘^’, let say powInd, then substring after powInd will be exponent(b1).
- Similarly, find out a2 and b2.
- if(a1 > 0 && a2 < 0), print M ( M will always be smaller).
- Similarly, if (a2 > 0 && a1 < 0), print N.
- else there will be need to use log to compare.
- The following formula will be used to calculate the log and arrive at a result that will be compared to determine which number is larger.
N = a1 * 10 ^ b1
Taking log base 10 both side
log N = log(a1) + b1 ———-(1)
Similarly, log(M) = log(a2) + b2 ———(2)
Subtract equation (1) from equation (2)
ans = (2) – (1)
ans = log(a1/a2) + b1 – b2
Therefore: int ans = log(a1/a2) + b1 – b2
- if a1 < 0, then ans = -ans. This is because both a1 and a2 are both negative.
- if ans < 0, print N.
- else if ans > 0, print M.
- else print Equal.
Below is the Java program to implement the above approach:
Time Complexity: O ( 1 )
According to the given constraints |a| can be of a maximum of 10 lengths of string and if it is negative, then it could be of 11 lengths, similarly b can also be of 11 digits. The maximum length of string could be 25 (11 +3+11), so we can consider extracting a and b of constant time operation.
Auxiliary Space: O ( 1 )
Please Login to comment...