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

Commit

Permalink
Fix issue #94: GCD function doens't work and realize GCD function (#100)
Browse files Browse the repository at this point in the history
* Fix issue #84: Permutation result is not right

* Fix issue #84: Permutation result is not right

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

* Fix issue #95: LCM function doesn't work and realize LCM function based on GCD function
  • Loading branch information
PAUL-Zf authored May 22, 2021
1 parent 80456b6 commit 65c514d
Showing 1 changed file with 55 additions and 0 deletions.
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

0 comments on commit 65c514d

Please sign in to comment.