Наименьший общий множитель

У меня есть текущее кодирование, которое раньше было goto, но мне сказали не использовать goto больше, поскольку его не одобряют. У меня возникли проблемы, которые меняют его, например, на цикл. Я новичок в С# и программировании вообще, поэтому некоторые из них для меня совершенно новые. Любая помощь будет оценена по достоинству. Фактический вопрос - ввести два числа и найти самый низкий общий кратный.

Вот оригинал с 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;
    }

   }

Ответы

Ответ 1

Попробуйте следующее:

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();
    }
}

Вывод:

Enter 2 numbers to find LCM
8
12
LCM of 8 and 12 is 24

Ответ 2

Здесь более эффективная и лаконичная реализация вычисления наименьшего общего множителя, которая использует его связь с величайшим общим фактором (он же величайший общий делитель). Эта функция Greatest Common Factor использует алгоритм Евклида, который более эффективен, чем решения, предлагаемые 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;
}

Для получения дополнительной информации см. статьи Википедии по вычислительной технике LCM и GCF.

Ответ 3

Попробуйте это

 int number1 = 20;
 int number2 = 30;
 for (tempNum = 1; ; tempNum++)
 {
   if (tempNum % number1 == 0 && tempNum % number2 == 0)
   {
       Console.WriteLine("L.C.M is - ");
       Console.WriteLine(tempNum.ToString());
       Console.Read();
       break;
    }
 }

// output -> L.C.M is - 60

Ответ 4

Вот одно рекурсивное решение. Это может быть на каком-то вопрос интервью. Я надеюсь, что это поможет

    public static int GetLowestDenominator(int a, int b, int c = 2)
    { 
        if (a == 1 | b == 1) {
            return 1;
        }
        else if (a % c == 0 & b % c == 0)
        {
            return c;
        }
        else if (c < a & c < b)
        {
            c += 1;
            return GetLowestDenominator(a, b, c);
        }
        else
        {
            return 0;
        }
    }

Ответ 5

        int num1, num2, mull = 1;

        num1 = int.Parse(Console.ReadLine());  
        num2 = int.Parse(Console.ReadLine());

        for (int i = 1; i <= num1; i++)
        {
            for (int j = 1; j <= num2; j++)
            {
                if (num1 * j == num2 * i)
                {
                    mull = num2 * i;
                    Console.Write(mull); 
                    return;
                }
            }
        }

Ответ 6

Вот очень оптимизированное решение для поиска LCM.

 private static int lcmOfNumbers(int num1, int num2)
    {
        int temp = num1 > num2 ? num1 : num2;
        int counter = 1;
        while (!((temp* counter++) % num1 == 0 && (temp* counter++) % num2 == 0)) {
        }
        return temp* (counter-2);
    }

Ответ 7

int n1 = 13;
int n2 = 26;

for (int i = 2; i <= n1; i++)
 {
    if (n1 % i == 0 && n2 % i == 0)
    {
    Console.WriteLine("{0} is the LCM of {1} and 
    {2}",i,n1,n2);
    break;
 }

  }