zoukankan      html  css  js  c++  java
  • nyoj 40

      题目:http://acm.nyist.edu.cn/JudgeOnline/status.php?pid=40

      求最大公约数和最小公倍数。。。

      思路:欧几里德算法求出最大公约数,即最大公约数 = gcd(a, b),然后再用(a*b)/gcd(a, b)即为最小公倍数。

      然而不知道为啥用递归的方法求gcd会WA。。。so,还是用迭代实现辗转相除法吧。。。

      如果不WA的话,递归代码:

    #include <bits/stdc++.h>
    int gcd(int a, int b)
    {
    	return a%b ? gcd(a, a%b) : b;
    }
    int main()
    {
    	int t, a, b;
    	scanf("%d", &t);
    	while (t--)
    	{
    		scanf("%d", &a);
    		scanf("%d", &b);
    		int e = gcd(a, b);
    		printf("%d %d
    ", e, a*b/e);
    	}
    	return 0;
    }
    

      AC代码:

    #include <bits/stdc++.h>
    int main()
    {
    	int t, a, b, c, d;
    	scanf("%d", &t);
    	while (t--)
    	{
    		scanf("%d", &a);
    		scanf("%d", &b);
    		c = a, d = b;
    		while(b)
    		{
    			int tem = b;
    			b = a%b;
    			a = tem;
    		}
    		printf("%d %d
    ", a, c*d/a);
    	}
    	return 0;
    }
    

      

  • 相关阅读:
    vue1.0
    网络抓包(四)
    物联网框架ServerSuperIO
    Solrcloud(Solr集群)
    机器学习1
    TCP/IP协议族(一)
    ElasticSearch(简称ES)
    工具
    线程本地变量的使用
    Features of Spring Web MVC
  • 原文地址:https://www.cnblogs.com/darkchii/p/9243565.html
Copyright © 2011-2022 走看看