Problem Description: Let’s look at the screenshot below.
I personally believe that this problem has multiple solutions and is suitable for practicing basic coding skills. Although it is clear to most that we are looking for the least common multiple, considering that some students participating in the assessment may not have reached fifth grade yet, I will provide several methods.For convenience in writing, I will use the English abbreviation gcd to represent the greatest common divisor.I will use lcm to replace the least common multiple (those interested can look up the full English term).Method 1: Shortest CodeSince the product of the gcd and lcm of a and b equals the product of a and b (however, based on my experience, most students may not know this conclusion even after learning fifth-grade math).We can directly call the C++ built-in __gcd function to find the least common multiple of a and b. Note that there are two underscores at the beginning of the function.
Method 2: Easiest to UnderstandWrite a while loop that increments a variable by 1 until that variable is a multiple of both m and n.
Method 3: Estimate the Upper Limit of lcmOnce we have the upper limit of lcm, we can use a for loop to enumerate and find the lcm.
Method 4: Reverse Enumeration to Find gcdEnumerate backwards to find gcd, then derive lcm.
Method 5: Implementing gcd using the Euclidean Algorithm with a while loop
Method 6: Custom gcd function implementing enumeration methodExperience the charm of using return to end a function directly.
Method 7: Custom gcd function implementing the Euclidean Algorithm (subtraction method)Experience the charm of recursion.
Alright, let’s wrap up today’s problem. I hope those with other methods will provide valuable feedback!