求最大公约数
辗转相除法(欧几里德法):
1.大数放在a中,小数放在b中,a/b的余数放在temp中,若temp等于0,则最大公约数为b;
2.如若不等于0,则a=b,b=temp进行循环直到temp=0,则b为最大公约数
例如15和9 15/9=1……6,9/6=1……3,6/3=0则最大公约数等于3
循环:
public class Java {
public static void main(String[] args) {
int a=9;
int b=15;
int m=a;
int n=b;
int temp=0;
if(a%b==0){
System.out.println(b);
}
if(a<b){
temp=a;
a=b;
b=temp;
}
temp=a%b;
while(temp!=0){
a=b;
b=temp;
temp=a%b;
}
System.out.println(b);
}
}
最小公倍数=两个数的乘积/最大公约数;
循环函数
public class JavaApplication29 {
public static void main(String[] args) {
int a=15;
int b=9;
System.out.println(gcd(15,9));
}
public static int gcd(int a,int b){
int temp=a%b;
while(temp!=0){
a=b;
b=temp;
temp=a%b;
}
return b;
}
}
递归:
public class Java {
public static void main(String[] args) {
int a=9;
int b=15;
System.out.println(gcd(15,9));
}
public static int gcd(int a,int b){
int temp=a%b;
if(temp==0){
return b;
}
else{
return gcd(b,a%b);
}
}
}
相减法(更相减损法)
1.如果a>b a=a-b;
2.如果 b>a b=b-a;
3.如果a=b,则a或b是最大公约数
4.如果 a!=b,则从1开始执行
5.循环判断的条件a!=b,直到a=b结束
public class Java{
public static void main(String[] args) {
int a=9;
int b=15;
System.out.println(gcd(15,9));
}
public static int gcd(int a,int b){
while(a!=b){
if(a>b){
a=a-b;
}
else{
b=b-a;
}
}
return a;
}
}
穷举法:
1.定义temp,把a.b中小的值给temp;
2.只要找到一个数能同时被,a.b整除则退出循环,否则temp–;
public class Java {
public static void main(String[] args) {
int a=9;
int b=15;
System.out.println(gcd(15,9));
}
public static int gcd(int a,int b){
int temp;
temp=(a>b)? b : a;
while(temp>0){
if(a%temp==0&&b%temp==0){
break;
}
else{
temp--;
}
}
return temp;
}
}