今天去面试一家公司,那个公司出了一道题是这样的:“用递归算法求N个正整数的最小公倍数”,可以用C#语言或是C语言写都可以,最好是用C#。我没有写出来,空在那儿,可想而知面试的结果肯定不会很好。不过我觉得仍有必要知道这个问题的答案,各位知道的能不能写出来,小弟不胜感激,在这里先谢了先。

解决方案 »

  1.   

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;namespace CommonM
    {
        class Program
        {
            static void Main(string[] args)
            {
                int[] Arr = { 4, 2, 45, 76, 78, 3, 9 };//待计算的整数数组
                System.Console.WriteLine(f(7, Arr));
                System.Console.Read();        }
            static int f(int n, int[] A)
            {
                if (n == 1)
                    return A[0];
                else
                {
                    int k = n;
                    k--;
                    return f1(f(n - 1, A), A[k]);
                }
            }
            static int f1(int a, int b)//求两个整数最小公倍数
            {
                int temp = a * b;
                while (a != b)
                {
                    if (a > b)
                        a = a - b;
                    else
                        b = b - a;
                }
                return temp / a;
            }
        }
    }
      

  2.   

    spotline给出的这个算法有问题,是错误的