Simple Interest with Exact Cents
Problem
The simple interest on a principal P, at a rate of R percent per year, for T years, is P * R * T / 100. Print it with exactly two digits after the decimal point. All inputs are whole numbers. Input: P, R and T on one line.
Constraints
- 1 <= P <= 10^6
- 1 <= R <= 100
- 1 <= T <= 50
Examples
Input
1000 5 2
Output
100.00
Input
1 1 1
Output
0.01
Solutions
Money is safest in whole cents. P * R * T is the interest in cents, so integer division and remainder give the two parts of the answer, without any floating-point error.
/*
* Problem : Simple interest.
* Input : P, R and T.
* Output : The interest with two decimals.
* Approach: Integer cents
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String[] solve(long a, long b, long m) {
// Step 1: The interest in cents is exactly P * R * T, because dividing by 100 and then multiplying by 100 cancels out.
long cents = a * b * m;
// Step 2: Whole money and the two digits of the cents are cut apart with integer division and remainder. No rounding is needed.
return new String[] {String.format("%d.%02d", cents / 100, cents % 100)};
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long a = scanner.nextLong();
long b = scanner.nextLong();
long m = scanner.nextLong();
System.out.println(String.join("\n", solve(a, b, m)));
}
}
Hints (2)
- Why is P * R * T the number of cents?
- What does %02d do?