一.求两个数的最大公约数 如何编程计算N个数的最大公约数(Greatest common divisor)呢?第一想法那便是两两计算,但是往往最简单的想法是不怎么靠谱的.下面用递归来解决.递归有一大好处,那便是递归非常符合人的思维,有时即使很复杂,但是依仗着递归的规律性,可以断定或推测出按递归做是正确的.如果说递归的性能低,我们可以采用备忘录法,用表记录过已经计算过的问题,避免二次计算,这样在一定程度上可以带来性能上的提升.我们可以先用递归实现,倘若在实际情况中发现性能问题,我们可以再进行优化.
一个简单的小算法来获取两个数的最大公约数, public class Test { public static void main(String[] args) { long result = gcd(15, 3); System.out.println(result); } public static long gcd(long m, long n) { while (n != 0) { long rem = m % n; m = n; n = rem; } return m; } }
两个数的最大公约数:不能大于两个数中的最小值,算法口诀:小的给大的,余数给小的,整除返回小的,即最大公约数,(res=max%min)==0? max=min,min=res return min; 两个数的最小公倍数:等于两数之和除以两个数的最大公约数 a*b/(LCM(a,b)); #include <iostream> using namespace std; /*求最大公约数,辗转相除法来求最小公倍数*/ int getLCM(int a, int b) { int max = (a
No Pain No Game Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 2000 Accepted Submission(s): 851 Problem Description Life is a game,and you lose it,so you suicide. But you can not kill yours
获得两个随机数(100以内),并放入数组中 public int[] getTwoRandom(){ int[] t = new int[2]; Random rand = new Random(); for(int i=0;i<t.length;i++) { t[i] = rand.nextInt(100); } return t; } 1.一般算法,连续整数检测法即从m和n中比较小的数开始一次遍历整数,如果有出现可以同时被m和n整除的数,就是最大公约数 //连续整数检测法 public in
求两个数 p 和 q 的最大公约数(greatest common divisor,gcd),利用性质 如果 p > q, p 和 q 的最大公约数 = q 和 (p % q)的最大公约数. 证明:见 http://blog.csdn.net/niushuai666/article/details/7278027 public class Euclid{ // recursive inplementation public static int gcd(int p, int q){ if(q =
using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("请输入一个数:"); int num1 = int.Parse(Console.ReadLine()); Console.WriteLine("请输入还有一个数:"); int num2 = int.Parse(Console.ReadLi
9.2 找出12和8的最大公约数和最小公倍数. public class Test { public static void main(String[] args) { getcommon_mu(12,8); getcommon_div(12,8); } //计算 最大公约数 和 最小公倍数 static void getcommon_mu(int n, int m) { int i, b, d;
问题分析: 用两个指针分别遍历即可. 问题求解: public class Solution { /** * @param nums1 an integer array * @param nums2 an integer array * @return an integer array */ public int[] intersection(int[] nums1, int[] nums2) { List<Integer> list = new ArrayList<Integer>