当前位置:网站首页>如何求最大公约数?
如何求最大公约数?
2022-08-09 12:25:00 【进击的李知因】
1、在1~m/2之间找约数,最后的约数即最大公约数
public class Case25_GreatestCommonDivisor{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入两个正整数:");
int m = in.nextInt();
int n = in.nextInt();
int gcd = 1;
if(m>n) //交换,确保m为较小者
{
m = m^n;
n = m^n;
m = m^n;
}
if(m == n || n%m == 0)
{
System.out.printf("%d与%d的最大公约数是%d\n",m,n,m);
System.exit(0);
}
//找约数,最后的即最大公约数
for(int i = 1; i <= m/2; i++)
if(m%i==0 && n%i==0)
gcd = i;
System.out.printf("%d与%d的最大公约数是%d\n",m,n,gcd);
}
}
2、在m/2~1之间找约数,找到就退出循环
for(int i = m/2; i > 0; i--)
if(m%i==0 && n%i==0)
{
gcd = i;
break;
}
3、欧几里德算法(辗转相除法)
public class Case25_GreatestCommonDivisor{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入两个正整数:");
int m = in.nextInt();
int n = in.nextInt();
if(m>n) //交换,确保m为较小者
{
m = m^n;
n = m^n;
m = m^n;
}
while(n%m != 0)
{
int temp = m;
m = n%m;
n = temp;
}
System.out.printf("%d与%d的最大公约数是%d\n",m,n,m);
}
}
边栏推荐
- 链表噩梦之一?5000多字带你弄清它的来龙去脉
- 使用RecyclerView实现三级折叠列表
- 超越CLIP的多模态模型,只需不到1%的训练数据!南加大最新研究来了
- Go 事,如何成为一个Gopher ,并在7天找到 Go 语言相关工作,第1篇
- FFmpeg库在win10上配置使用(不配置libx264)
- JVM常用监控工具解释以及使用
- 荣耀携手Blue Yonder,加快企业战略增长
- Introduction to Flutter advanced trip Dialog&Toast (10)
- 中科院打脸谷歌:普通电脑追上量子优越性,几小时搞定原本要一万年的计算...
- ViewPager fragments of nested data blank page abnormal problem analysis
猜你喜欢
ABAP 报表中如何以二进制方式上传本地文件试读版
合并两个有序列表
Flutter entry and advanced tour (6) Layout Widget
GPT-3组合DALL·E,60秒内搞定游戏设定和原型动画!网友看后:这游戏想玩
AQS Synchronization Component - FutureTask Analysis and Use Cases
史上最猛“员工”,疯狂吐槽亿万富翁老板小扎:那么有钱,还总穿着同样的衣服!...
Go 事,如何成为一个Gopher ,并在7天找到 Go 语言相关工作,第1篇
Flutter Getting Started and Advanced Tour (3) Text Widgets
Too much volume... Tencent was asked on the side that the memory was full, what would happen?
Ten minutes to teach you how to use VitePress to build and deploy a personal blog site
随机推荐
技术分享 | 接口自动化测试如何处理 Header cookie
Flutter入门进阶之旅(十)Dialog&Toast
字符串转换整数 (atoi)
h264 protocol
位图与位运算
AQS Synchronization Component - FutureTask Analysis and Use Cases
8、IDEA提交代码出现: Fetch failed fatal: Could not read from remote repository
1小时直播招募令:行业大咖干货分享,企业报名开启丨量子位·视点
Flutter入门进阶之旅(一)-初识Flutter
Flutter Getting Started and Advanced Tour (8) Button Widget
如何修改data work上jdbc驱动的版本
How to save Simulink simulation model as image or PDF
Flutter entry and advanced tour (6) Layout Widget
00后写个暑假作业,被监控成这笔样
罗振宇折戟创业板/ B站回应HR称用户是Loser/ 腾讯罗技年内合推云游戏掌机...今日更多新鲜事在此...
go基础之web获取参数
Adalvo收购其首个品牌产品Onsolis
[Microservice ~ Remote Call] Integrate RestTemplate, WebClient, Feign
JVM常用监控工具解释以及使用
About the handling of variable parameters in the Retrofit network request URL