如何在 C# 中列出数的根

how to list roots of number in c#

我正在尝试编写一个代码来列出给定数字的根。 这是 I did 到目前为止的内容。我得到的结果是 2*2*5*5,这是真的,但我想得到这个:2^2*5^2

public partial class Form1 : Form
{
    List<int> divisor;

    public Form1()
    {
        InitializeComponent();
    }

    private void list_Click(object sender, EventArgs e)
    {
        int number;
        divisor = new List<int>();

        showroot.Text = "";
        number = Int32.Parse(usernum.Text);

        for (int i = 2; i <= number; i++)
        {
            if (number % i == 0)
            {
                divisor.Add(i);
                number = number / i;
                i = 1;
            }
        }

        for (int i = 0; i < divisor.Count; i++)
        {
            print(""+ divisor[i]);
        }
    }

    private void print(String text)
    {
        if (showroot.Text != "")
        {
            showroot.Text = showroot.Text + "*" + text;
        }
        else
        {
            showroot.Text = text;
        }
    }
  }

我试图检查有多少相同的根并以两个为嵌套的语句进行计数,但这又带来了另一个错误。

for (int i = 0; i < divisor.Count; i++) {
  for (int a = 0; i < divisor.Count; a++) {
    if (i == a) {
      base[i]++;
    }
  }
}

怎么办?

天真的实现方式是将您的 for 更改为:

for (int i = 2; i <= number; i++)
{
    count = 0;
    while (number % i == 0)
    {            
        number = number / i;
        count++;
    }

    if (count > 0)
    {
       divisor.Add(i);
       powers.Add(count);
    }
 }

但是可以做很多优化。

将任务分成易于实施的部分,提取方法

首先,让我们收集所有质数约数(因数可以重复):

private static IEnumerable<int> AllPrimeDivisors(int value) {
  if (value <= 1)
    yield break;

  for (; value % 2 == 0; value /= 2)
    yield return 2;

  int n = (int)(Math.Sqrt(value) + 0.5);

  for (int d = 3; d <= n; d += 2) {
    while (value % d == 0) {
      yield return d;

      value /= d; 
      n = (int)(Math.Sqrt(value) + 0.5);
    }
  }

  if (value > 1)
    yield return value;
}

然后按要求的格式组合它们(我们应该 GroupBy 相同 - 重复 - 除数并以 divisordivisor^power 格式表示它们)

private static string Solve(int value) {
  var terms = AllPrimeDivisors(value)
    .GroupBy(divisor => divisor)
    .Select(group => group.Count() == 1 
       ? $"{group.Key}"
       : $"{group.Key}^{group.Count()}");

  return string.Join("*", terms);  
}

最后加上UI:

private void list_Click(object sender, EventArgs e) {
  if (int.TryParse(usernum.Text, out var number))
    showroot.Text = Solve(number);
  else
    showroot.Text = "Incorrect Input, Syntax Error";
}

测试:

int[] tests = new int[] {
  3, 5, 9, 12, 16, 41, 81, 100,  
};

var result = tests
  .Select(item => $"{item,3} == {Solve(item)}");

Console.Write(string.Join(Environment.NewLine, result)); 

结果:

  3 == 3
  5 == 5
  9 == 3^2
 12 == 2^2*3
 16 == 2^4
 41 == 41
 81 == 3^4
100 == 2^2*5^2