Ai
1 Star 0 Fork 3

aiobc/Algorithms

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
LCM.java 772 Bytes
一键复制 编辑 原始数据 按行查看 历史
Rafael Chaves 提交于 2020-02-03 02:07 +08:00 . Adopt standard Java project layout (#120)
/**
* An implementation of finding the LCM of two numbers
*
* <p>Time Complexity ~O(log(a + b))
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.algorithms.math;
public class LCM {
// Finds the greatest common divisor of a and b
private static long gcd(long a, long b) {
return b == 0 ? (a < 0 ? -a : a) : gcd(b, a % b);
}
// Finds the least common multiple of a and b
public static long lcm(long a, long b) {
long lcm = (a / gcd(a, b)) * b;
return lcm > 0 ? lcm : -lcm;
}
public static void main(String[] args) {
System.out.println(lcm(12, 18)); // 36
System.out.println(lcm(-12, 18)); // 36
System.out.println(lcm(12, -18)); // 36
System.out.println(lcm(-12, -18)); // 36
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/aiobc/Algorithms.git
git@gitee.com:aiobc/Algorithms.git
aiobc
Algorithms
Algorithms
master

搜索帮助