package com.wener;
/**
* 使用辗转相除法求
*/
import java.util.Scanner;
public class HomeWork01 {
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
System.out.print("请输入第一个整数:\n");
int a = scan.nextInt();
System.out.print("请输入第二个整数:\n");
int b = scan.nextInt();
if(a>0&&b>0) {
Max_Min(a,b);
}else {
System.out.println("请输入两个正整数!");
}
}
public static void Max_Min(int a,int b){
int i = a;
int j = b;
int x =0,y =0;
if(a < b){
x = b;
b = a;
a = x;
}
while(b != 0){
y = a % b;
a = b;
b = y;
}
//最小公倍数
int t = i * j / a;
System.out.println(i+"和"+j+"的最大公约数为:"+ a);
System.out.println(i+"和"+j+"的最小公倍数为:"+ t);
}
}
package com.wener;
/**
* 使用相减法求
*/
import java.util.Scanner;
public class HomeWork02 {
public static void main(String[]args) {
int z=0;
Scanner scan = new Scanner(System.in);
System.out.print("请输入第一个整数:\n");
int x = scan.nextInt();
System.out.print("请输入第二个整数:\n");
int y = scan.nextInt();
if(x>0&&y>0) {
z=Subtraction(x,y);
System.out.println("最大公约数为 : "+z);
System.out.println("最小公倍数为: "+(x*y/z));
}else {
System.out.println("请输入两个正整数!");
}
}
public static int Subtraction(int x,int y){
while(x!=y){
if(x>y){
x=x-y;
}
else{
y=y-x;
}
}
return x;
}
}
package com.wener;
/**
* 使用穷举法求
*/
import java.util.Scanner;
public class HomeWork03 {
public static void main(String[]args) {
int z=0;
Scanner scan = new Scanner(System.in);
System.out.print("请输入第一个整数:\n");
int x = scan.nextInt();
System.out.print("请输入第二个整数:\n");
int y = scan.nextInt();
if(x>0&&y>0) {
z = divisor(x,y);
z = multiple(x,y);
System.out.println("最大公约数为 : "+divisor(x,y));
System.out.println("最小公倍数为: "+multiple(x,y));
}else {
System.out.println("请输入两个正整数!");
}
}
public static int divisor(int x,int y){
int z;
for(z=x;z>0;z--){
if(x%z==0&&y%z==0){
break;
}
}
return z;
}
public static int multiple(int x,int y){
int z;
for(z=x;;z++){
if(z%x==0&&z%y==0){
break;
}
}
return z;
}
}
package com.wener;
import java.util.Scanner;
/*
* 求多个正整数的最大公约数和最小公倍数
*/
public class HomeWork04 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入第一个数:");
int a=sc.nextInt();
System.out.println("请输入第二个数:");
int b=sc.nextInt();
System.out.println("请输入数的个数并且和每个数:");//n为数组的个数
int n=sc.nextInt();
int[] num=new int[n];
for(int i=0;i<n;i++) {
num[i]=sc.nextInt();
}
System.out.println(n+"个数的最大公约数为"+getMoreBigDiv(num, n));
System.out.println(n+"个数的最小公倍数"+getMoreSmallMul(num, n));
}
public static int getBigDiv(int a, int b) {// 求两个数的最大公约数
if (b == 0)
return a;
return getBigDiv(b, a % b);
}
public static int getSmallMul(int a, int b) {// 求两个数的最小公倍数
return (a * b) / getBigDiv(a, b);
}
public static int getMoreBigDiv(int num[], int n) { // 求多个数的最大公约数
if (n == 1)
return num[n - 1];
return getBigDiv(num[n - 1], getMoreBigDiv(num, n - 1));
}
public static int getMoreSmallMul(int num[], int n) {// 求多个数的最小公倍数
if (n == 1)
return num[n - 1];
return getSmallMul(num[n - 1], getMoreSmallMul(num, n - 1));
}
}
求2个及多个正整数的最大公约数和最小公倍数的三种方法
最新推荐文章于 2022-11-03 20:50:49 发布