【问题标题】:C# find the greatest common divisorC#求最大公约数
【发布时间】:2022-03-02 04:51:13
【问题描述】:

“两个整数的最大公约数是两个整数中的每一个均分的最大整数。编写返回两个整数的最大公约数的方法 Gcd。将该方法合并到从用户读取两个值的应用程序中并显示结果。”

(这不是作业,只是我正在使用的书中的一个练习)

你能帮我解决这个问题吗?这是我到目前为止所得到的。

(编辑 - 我可以提交这两个数字,但它不会为我计算 Gcd)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Greatest_Common_Divisor
{
class Program
{

    static int GetNum(string text)
    {
        bool IsItANumber = false;
        int x = 0;
        Console.WriteLine(text);

        do
        {
            IsItANumber = int.TryParse(Console.ReadLine(), out x);

        } while (!IsItANumber);

        return x;
    }
    static void Main(string[] args)
    {
        string text = "enter a number";
        int x = GetNum(text);
        text = "enter a second number";
        int y = GetNum(text);


        int z = GCD(x, y);
        Console.WriteLine(z);
    }

    private static int GCD(int x, int y)
    {
        int v = 0;
        int n = 0;

        v = GetGreatestDivisor(x, y);


        return v;

    }

    static int GetGreatestDivisor(int m, int h)
        {

            do
            {
                for (int i = m; i <= 1; i--)



                    if (m%i == 0 && h%i == 0)
                    {
                        int x = 0;
                        x = i;

                        return x;
                    }
            } while (true);
            return m;
        }

  }
}

【问题讨论】:

  • 您的代码是不工作还是不完整?
  • 这里有什么问题?
  • 我可以提交这两个数字,但它不会为我计算 Gcd
  • 您应该查看Euclidean algorithm。
  • for (int i = m; i &lt;= 1; i--) 在m &gt; 1 时不会执行,你的意思是i &gt;= 1。

标签: c# math


【解决方案1】:

这是Euclidean algorithm 的实现,它返回最大公约数而不执行任何堆分配。

如果需要,您可以将ulong 替换为uint。使用无符号类型,因为该技术不适用于有符号值。如果您知道您的 a 和 b 值不是负数,则可以改用 long 或 int。

private static ulong GCD(ulong a, ulong b)
{
    while (a != 0 && b != 0)
    {
        if (a > b)
            a %= b;
        else
            b %= a;
    }

    return a | b;
}

此方法在我的metadata-extractor 库中使用,它与unit tests 相关联。

【讨论】:

  • 这是页面上的最佳答案;它不执行任何昂贵且无关的递归调用,并且实际上回答了 OP 的特定问题(不像其他一些答案,由于某种原因离题了一组 GCD)。
  • 他们计算一个集合的 GCD,因为他们从一个单独的问题的答案中复制和粘贴他们不理解的代码。
  • 又好又干净 - 没有混合 LINQ 汤。这样,正是我在寻找自己的小“困境”。 :D
  • 哦,这确实适用于负输入:只需在进入 while 循环之前翻转负值的符号... if(a
  • 最后一行可以写成:“return a | b;” .由于其中一个始终为零,因此对两者执行 OR 运算将产生非零值。
【解决方案2】:

使用 LINQ 的聚合方法:

static int GCD(int[] numbers)
{
    return numbers.Aggregate(GCD);
}

static int GCD(int a, int b)
{
    return b == 0 ? a : GCD(b, a % b);
}

注意:上面的答案是从Greatest Common Divisor from a set of more than 2 integers接受的答案中借来的。

【讨论】:

  • 这是不正确的。您不能将此答案拆分为 LINQ 和非 LINQ,解决方案是两种方法一起工作。第一种方法在Aggregate调用中调用第二种方法,这有点混乱,因为名字是一样的。
  • 很高兴回答这个问题,Karl。你的回答确实不正确。
  • @DonLarynx 在最近一次编辑后,这个答案是否仍然不正确?似乎至少第二个功能对我有用,但我肯定是错的。
【解决方案3】:

你可以试试this:

static int GreatestCommonDivisor(int[] numbers)
{
    return numbers.Aggregate(GCD);
}

static int GreatestCommonDivisor(int x, int y)
{
return y == 0 ? x : GreatestCommonDivisor(y, x % y);
}

【讨论】:

  • 返回 x*y == 0 ? x : GreatestCommonDivisor(y, x % y);这个版本有更准确的
【解决方案4】:

试试这个:

public static int GCD(int p, int q)
{
    if(q == 0)
    {
         return p;
    }

    int r = p % q;

    return GCD(q, r);
}

【讨论】:

    【解决方案5】:
    public class GCD 
    {        
        public int generalizedGCD(int num, int[] arr)
        {
             int gcd = arr[0]; 
    
            for (int i = 1; i < num; i++) {
                gcd = getGcd(arr[i], gcd); 
            }
    
            return gcd; 
        }    
        public int getGcd(int x, int y) 
        { 
            if (x == 0) 
                return y; 
            return getGcd(y % x, x); 
        } 
    }
    

    【讨论】:

      【解决方案6】:
      By using this, you can pass multiple values as well in the form of array:-
      
      
      // pass all the values in array and call findGCD function
          int findGCD(int arr[], int n) 
          { 
              int gcd = arr[0]; 
              for (int i = 1; i < n; i++) {
                  gcd = getGcd(arr[i], gcd); 
      }
      
              return gcd; 
          } 
      
      // check for gcd
      int getGcd(int x, int y) 
          { 
              if (x == 0) 
                  return y; 
              return gcd(y % x, x); 
          } 
      

      【讨论】:

        【解决方案7】:
        List<int> gcd = new List<int>();
        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();
        

        【讨论】:

          【解决方案8】:

          如果效率不是一个大问题,这将完成这项工作。

          // gets greatest common divisor of A and B. 
          var GCD=Enumerable.Range(1,Math.Min(A,B)).Last(n=>(A%n | B%n)==0);
          

          【讨论】:

            【解决方案9】:
            int[] nums = new int[] {6,12,24,48};
            int GCD(int a, int b) => b == 0 ? a : GCD(b, a % b);
            int FindGCD(int[] numbers) => numbers.Aggregate(GCD);
            
            Console.WriteLine($"List of numbers ({String.Join(',',nums)})");
            Console.WriteLine($"Smallest number: {nums.Min()}");
            Console.WriteLine($"Largest number: {nums.Max()}");
            Console.WriteLine($"Greatest common devisor of {nums.Min()} and {nums.Max()}: {GCD(nums.Min(),nums.Max())}");
            Console.WriteLine($"Aggregate common devisor of array ({String.Join(',',nums)}): {FindGCD(nums)}");
            

            数字列表(6、12、24、48)

            最小的数:6

            最大数:48

            6 和 48 的最大公约数:6

            数组(6,12,24,48)的聚合公约数:6

            【讨论】:

              【解决方案10】:

              这是一个简单的解决方案。 您可以使用BigInteger 获得最大公约数。只是不要忘记在代码顶部添加using System.Numerics;。

              using System.Numerics;
              
              public class Program{
                  public static void Main(String[] args){
                      int n1 = 1;
                      int n2 = 2;
              
                      BigInteger gcd = BigInteger.GreatestCommonDivisor(n1,n2);
                      Console.WriteLine(gcd);
                  }
              }
              

              Offical Documentation

              【讨论】:

                【解决方案11】:
                using System;
                
                //Write a function that returns the greatest common divisor (GCD) of two integers
                
                namespace GCD_of_Two_Numbers
                {
                    class Program
                    {
                        public static void Gcd(int num1, int num2)
                        {
                            int[] temp1 = new int[num1];
                            int[] temp2 = new int[num2];
                            int[] common = new int[10];
                
                            for(int i=2;i<num1/2;i++)
                            {
                                if(num1 % i ==0)
                                {
                                    temp1[i] = i;
                                }
                            }
                
                            for (int i = 2; i < num2/2; i++)
                            {
                                if (num2 % i == 0)
                                {
                                    temp2[i] = i;
                                }
                            }
                            int len = temp1.Length + temp2.Length;
                            for(int i=0;i<len;i++)
                            {
                                if(temp1[i]==temp2[i])
                                {
                                    common[i] = temp1[i];
                                }
                            }
                
                            int max_number = common[0];
                            for(int i=0;i<common.Length;i++)
                            {
                                if(max_number < common[i])
                                {
                                    max_number = common[i];
                                }
                            }
                
                            Console.WriteLine($"The Greatest Common Diviser is {max_number}");
                        }
                        
                        static void Main(string[] args)
                        {
                            Gcd(32, 8);
                        }
                    }
                }
                

                【讨论】:

                  【解决方案12】:
                      int a=789456;
                  
                  
                      int b=97845645;
                      if(a>b)     
                      {
                  
                      }
                      else
                      {
                          int temp=0;
                          temp=a;
                          a=b;
                          b=temp;
                      }
                      int x=1;
                      int y=0 ;
                  
                      for (int i =1 ; i < (b/2)+1 ; i++ )
                      {
                  
                          if(a%i==0)
                          {
                               x=i;
                          }
                          if(b%i==0)
                          {
                               y=i;
                          }
                          if ((x==y)& x==i & y==i & i < a)
                          {
                              Console.WriteLine(i);
                          }
                  
                      }
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2020-12-07
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2010-10-01
                    相关资源
                    最近更新 更多