标签:java Scanner nextInt 公倍数 System int 最大公约数 sc public
1.首先,最大公约数利用p和q之间求余,将q赋给p,再将余数 r 赋给q,如此循环下去,当q为0,最终的q即为最大公约数。
2.其次,最小公倍数可以由两个数的乘积除以两个数的最大公约数得到。
java程序如下所示:
1.暴力法:
public void run(){
Scanner sc = new Scanner(System.in);
int a;
int b;
int cur = 1;
while (sc.hasNext()){
a = sc.nextInt();
b = sc.nextInt();
for (int i = 1; i <= Math.min(a,b); i++) {
if(a % i == 0 && b % i == 0){
cur = i;
}
}
System.out.println((a * b) / cur);
cur = 1;
}
}
2.递归法
public static int gcd1(int p, int q){
// 若q为0,则最大公约数为p
if(q == 0) {
return p;
}
int r = p % q;
return gcd1(q, r);
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(Main.gcd1(a,b));
}
3.辗转相除法
public static int gcd2(int p, int q){
int r;
while(q != 0){
r = p % q;
p = q;
q = r;
}
return p;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(Main.gcd2(a,b));
}
public static int lcm(int p, int q) {
int p1 = p;
int q1 = q;
while (q != 0) {
int r = p % q;
p = q;
q = r;
}
return (p1 * q1) / p;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(Main.lcm(a,b));
}
fanyut521
发布了6 篇原创文章 · 获赞 1 · 访问量 620
私信
关注
标签:java,Scanner,nextInt,公倍数,System,int,最大公约数,sc,public 来源: https://blog.csdn.net/xun_zhao_t521/article/details/104180695
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。