Divide
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.13;
contract Divide {
uint256 public constant PERCENTAGE_INTEREST = 3;
/**
* The calculate interst function is buggy because of how it calculates interest of amount parsed into it
* Make it return the right value.
*/
function calculateInterest(uint256 amount) external pure returns (uint256) {
uint256 x = (PERCENTAGE_INTEREST /100) * amount;
return x;
}
}
Problem Analysis
The problem is that, you will get 0 when you using an integer divide by a number greater than itself. In this case we need to do multiple before devide.
Coding
1
2
3
4
function calculateInterest(uint256 amount) external pure returns (uint256) {
uint256 x = PERCENTAGE_INTEREST * amount / 100;
return x;
}
Test
1
2
3
4
5
6
7
8
9
10
➜ Divide git:(main) ✗ forge test -vvv
[⠊] Compiling...
No files changed, compilation skipped
Ran 1 test for test/Divide.t.sol:DivideTest
[PASS] testDivide() (gas: 8487)
Suite result: ok. 1 passed; 0 failed; 0 skipped; finished in 4.85ms (447.83µs CPU time)
Ran 1 test suite in 193.12ms (4.85ms CPU time): 1 tests passed, 0 failed, 0 skipped (1 total tests)
Great, we pass the test case!
Reference: Solidity Exercise - Divide