最不常见的多重

Tri*_* M. 19 c# lcm

我有当前的编码,曾经是一个goto但我被告知不再使用goto,因为它不赞成.我有麻烦改变它说一段时间循环.我对C#和一般编程都很陌生,所以这对我来说是一些全新的东西.任何帮助,将不胜感激.实际问题是输入两个数字并找到最低的公倍数.

这是带goto的原文:

BOB:
    if (b < d)
    {                
        a++;
        myInt = myInt * a;
        b = myInt;
        myInt = myInt / a;

        if (b % myInt2 == 0)
        {
            Console.Write("{0} ", h);
            Console.ReadLine();
        }

    }
    if (d < b)
    {
        c++;
        myInt2 = myInt2 * c;
        d = myInt2;
        myInt2 = myInt2 / c;

        if (d % myInt == 0)
        {
            Console.Write("{0} ", t);
            Console.ReadLine();
        }
        else
        {
            goto BOB;
        }

    }
    else
    {
        goto BOB;
    }

   }
Run Code Online (Sandbox Code Playgroud)

Aff*_*Owl 35

这是一个更有效和简洁的最小公倍数计算实现,利用它与最大公因数(又名最大公约数)的关系.这个最大公共因子函数使用欧几里德算法,它比user1211929或Tilak提供的解决方案更有效.

static int gcf(int a, int b)
{
    while (b != 0)
    {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

static int lcm(int a, int b)
{
    return (a / gcf(a, b)) * b;
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅维基百科有关计算LCMGCF的文章.

  • 有关两个以上的数字,请访问http://stackoverflow.com/a/29717490/68936 (3认同)

use*_*929 11

试试这个:

using System;

public class FindLCM
{
    public static int determineLCM(int a, int b)
    {
        int num1, num2;
        if (a > b)
        {
            num1 = a; num2 = b;
        }
        else
        {
            num1 = b; num2 = a;
        }

        for (int i = 1; i < num2; i++)
        {
            if ((num1 * i) % num2 == 0)
            {
                return i * num1;
            }
        }
        return num1 * num2;
    }

    public static void Main(String[] args)
    {
        int n1, n2;

        Console.WriteLine("Enter 2 numbers to find LCM");

        n1 = int.Parse(Console.ReadLine());
        n2 = int.Parse(Console.ReadLine());

        int result = determineLCM(n1, n2);

        Console.WriteLine("LCM of {0} and {1} is {2}",n1,n2,result);
        Console.Read();
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Enter 2 numbers to find LCM
8
12
LCM of 8 and 12 is 24
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,但我想知道我在做什么,而不仅仅是从别人那里拿走. (11认同)

Adr*_*zak 6

嘿,如果有人需要更现代的东西:)

public static class MathHelpers
{
    public static T GreatestCommonDivisor<T>(T a, T b) where T : INumber<T>
    {
        while (b != T.Zero)
        {
            var temp = b;
            b = a % b;
            a = temp;
        }

        return a;
    }

    public static T LeastCommonMultiple<T>(T a, T b) where T : INumber<T>
        => a / GreatestCommonDivisor(a, b) * b;
    
    public static T LeastCommonMultiple<T>(this IEnumerable<T> values) where T : INumber<T>
        => values.Aggregate(LeastCommonMultiple);
}
Run Code Online (Sandbox Code Playgroud)