C# find the greatest common divisor

后端 未结 9 1520
夕颜
夕颜 2020-12-02 23:11

\"The greatest common divisor of two integers is the largest integer that evenly divides each of the two numbers. Write method Gcd that returns the greatest common divisor o

9条回答
  •  北海茫月
    2020-12-02 23:53

    List gcd = new List();
    int n1, n2;
    
    bool com = false;
    
    Console.WriteLine("Enter first number: ");
    n1 = int.Parse(Console.ReadLine());
    Console.WriteLine("Enter second number: ");
    n2 = int.Parse(Console.ReadLine());
    
    for(int i = 1; i <= n1; i++)
    {
        if(n1 % i == 0 && n2% i == 0)
        {
            gcd.Add(i);
        }
    
        if(i == n1)
        {
            com = true;
        }
    }
    
    if(com == true)
    {
        Console.WriteLine("GCD of {0} and {1} is {2}.", n1, n2, gcd[gcd.Count - 1]);
    }
    Console.ReadLine();
    

提交回复
热议问题