Skip to content
This repository has been archived by the owner on Mar 29, 2023. It is now read-only.

Fix issue #94: GCD function doens't work and realize GCD function #100

Merged
merged 5 commits into from
May 22, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -479,9 +479,64 @@ void setState(CalculatorState state) {
mCurrentState = state;
}

/**
* Parse out the two integers entered by the user and execute the lcm
* algorithm to solve the least common multiple of these two integers.
* @param nums
* The string entered by the user, including parentheses and commas.
* @return The least common multiple of two integers
*/

public String executeLCM(String nums){
int num1 = Integer.parseInt(nums.split(",")[0].trim());
int num2 = Integer.parseInt(nums.split(",")[1].trim());
int gcd = gcd(num1, num2);
//lcm(a,b) = |a*b| / gcd(a,b) (According to Wikipedia: https://en.wikipedia.org/wiki/Least_common_multiple)
int lcm = (num1 * num2) / gcd;
return lcm + "";
}

/**
* Parse out the two integers entered by the user and execute the gcd
* algorithm to solve the greatest common factor of these two integers.
* @param nums
* The string entered by the user, including parentheses and commas.
* @return The greatest common divisor of two integers
*/

public String executeGCD(String nums){
int num1 = Integer.parseInt(nums.split(",")[0].trim());
int num2 = Integer.parseInt(nums.split(",")[1].trim());
int res = gcd(num1, num2);
return res + "";
}

/**
* Recursively solve the greatest common factor of two integers.
* @param a The first integer entered by the user.
* @param b The second integer entered by the user.
* @return The greatest common divisor of two integers.
*/

public static int gcd(int a, int b){
if (b == 0) {
return a;
}
return gcd(b, a % b);
}

@Override
public void onEvaluated(String expr, String result, int resultId) {
if (resultId == LogicEvaluator.RESULT_OK) {
//Parse user input to get the function to be executed and operand.
String operator = expr.substring(0,3).toLowerCase();
String nums = expr.substring(4, expr.length() - 1);
if(operator.equals("gcd")){
result = "$$" + executeGCD(nums) + "$$";
}
if(operator.equals("lcm")){
result = "$$" + executeLCM(nums) + "$$";
}
if (mCurrentState == CalculatorState.EVALUATE) {
onResult(result);
saveHistory(expr, result, true);
Expand Down