What would be the easiest way to calculate Greatest Common Divisor and Least Common Multiple on a set of numbers? What math functions can be used to find this information?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
There is an Euclid's algorithm for GCD,
By the way,
a
andb
should be greater or equal0
, and LCM =|ab| / GCF(a, b)
here, first for loop is for getting every numbers starting from '2'. then if statement check whether the number(i) divides lcm if it does then it skip that no. and if it doesn't then next for loop is for finding a no. which can divides the number(i) if this happens we don't need that no. we only wants its extra factor. so here if the flag is true this means there already had some factors of no. 'i' in lcm. so we divide that factors and multiply the extra factor to lcm. If the number isn't divisible by any of its previous no. then when simply multiply it to the lcm.
There are no build in function for it. You can find the GCD of two numbers using Euclid's algorithm.
For a set of number
Apply it recursively.
Same for LCM:
If you can use Java 8 (and actually want to) you can use lambda expressions to solve this functionally:
I oriented myself on Jeffrey Hantin's answer, but
numbers
-Array into functional syntax, which is more compact and IMO easier to read (at least if you are used to functional programming)This approach is probably slightly slower due to additional function calls, but that probably won't matter at all for the most use cases.
Basically to find gcd and lcm on a set of numbers you can use below formula,
Meanwhile in java you can use euclid's algorithm to find gcd and lcm, like this
You can refer this resource to find examples on euclid's algorithm.