Java算法:计算两个数的最小公倍数?
发布网友
发布时间:2022-04-30 12:08
我来回答
共5个回答
热心网友
时间:2022-06-23 20:56
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class zxgbs {
/**
* @param args
*/
public static void main(String[] args) {
//两个数的最小公倍数
int n1, n2, d;
String str;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
System.out.print("输入正整数n1:");
str = br.readLine();
n1 = Integer.parseInt(str);
System.out.print("输入正整数n2: ");
str = br.readLine();
n2 = Integer.parseInt(str);
if (n1 > n2) {
d = n1;
} else {
d = n2;
}
for(int i = d; i <= n1 * n2; i ++) {
if(i % n1 == 0 && i % n2 == 0) {
System.out.println(n1 + "和" + n2 + "的最小公倍数是:" + i);
break;
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
热心网友
时间:2022-06-23 20:57
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class zxgbs {
/**
* @param args
*/
public static void main(String[] args) {
//两个数的最小公倍数
int n1, n2, d;
String str;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
System.out.print("输入正整数n1:");
str = br.readLine();
n1 = Integer.parseInt(str);
System.out.print("输入正整数n2: ");
str = br.readLine();
n2 = Integer.parseInt(str);
if (n1 > n2) {
d = n1;
} else {
d = n2;
}
for(int i = d; i <= n1 * n2; i ++) {
if(i % n1 == 0 && i % n2 == 0) {
System.out.println(n1 + "和" + n2 + "的最小公倍数是:" + i);
break;
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
热心网友
时间:2022-06-23 20:57
public static void main(String[] args){
int a = 8;
int b = 6;
for(int i=1; i<=b; i++){
int j = a*i%b;
if(j==0){
System.out.println(" a和b的最小公倍数是 "+(a*i));
break;
}
}
}
忘了小学学的公式是怎么写的了.这个好象是最小倍数吧?
热心网友
时间:2022-06-23 20:58
public static int *(int m,int n){
if (m<n){
int t = n;
n = m;
m = t;
}
int r;
do{
r = m % n;
m = n;
n = r;
}while (r != 0);
return m;
}
public static void main(String[] args){
int a = 8;
int b = 6;
System.out.println(" a和b的最小公倍数是 "+(a*b/*(a,b)));
}
}
}
热心网友
时间:2022-06-23 20:59
Java求三个数的最小公倍数算法优化(极限性能)
网页链接