简体   繁体   English

找到最大因素的程序

[英]Program that finds the largest prime factor

So I wrote a code for finding the largest factor for my learning procces on Project Euler and it worked fine and I got the right answer. 因此,我编写了一个代码,以寻找对我的欧拉计划学习过程影响最大的因素,并且效果很好,我得到了正确的答案。 Tho I saw diffrent solutions and they were "longer" and looked more complicated. 我看到了不同的解决方案,它们“更长”并且看起来更加复杂。 So my question is, is there anything my code is no taking care of for lets say different number or is there a better way to do this task? 所以我的问题是,我的代码有什么需要照顾的吗?让我们说不同的数字吗?或者有更好的方法来执行此任务吗? I am trying to learn different ways of solving problems to get better at programming so I wonder if I should have done that code in a different way. 我正在尝试学习解决问题的不同方法,以便更好地进行编程,所以我想知道是否应该以其他方式来完成该代码。

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

namespace prime_factor
{
  class Program
  {
    static void Main(string[] args)
    {
        long n = 600851475143;
        int largest = 0;
        for (int i = 1; i<=n; i++)
        {
            if (n%i == 0)
            {
                Console.WriteLine(i);
                n /= i;
                largest = i;

            }
        }
        Console.WriteLine(largest);
        Console.ReadLine();
    }
  }
}

If you divide n by f every time you find a factor, you will automatically find only prime factors. 如果每次找到一个因子都用n除以f ,则将自动仅找到素因子。 Here's pseudocode that you can translate to your favorite language: 您可以将以下伪代码转换为自己喜欢的语言:

function factors(n)
    f := 2; fs := []
    while f * f <= n
        if n % f == 0
            fs := fs ++ f
            n := n / f
        else
            f := f + 1
    fs := fs ++ n
    return fs

Here fs is a linked list of factors, and ++ is the list-append operation. 这里fs是因子的链接列表,而++是list-append操作。 You can see a Python implementation here . 您可以在此处看到Python实现。

There are better ways to find factors, but this is sufficient for the Project Euler problem that you are trying to solve. 有更好的方法来查找因素,但这足以解决您试图解决的欧拉计画问题。 If you are interested in programming with prime numbers, you might enjoy this essay at my blog. 如果您对使用质数编程感兴趣,那么可以在我的博客上喜欢这篇文章

I like it - you get around checking if i is prime, which is the most complicated part! 我喜欢它-您可以检查i是否素数,这是最复杂的部分! If it were not prime, you would have already divided out it's composite factors. 如果不是素数,您可能已经将其分解为综合因素。

However, I think there are cases where a non-prime i can sneak in - where multiples of prime factors divide your n . 但是,我认为在某些情况下i可以潜入非素数-素数的倍数将n Try n = 36 (since 36 == 2^2 * 3^2). 尝试n = 36 (因为36 == 2 ^ 2 * 3 ^ 2)。 I think your algorithm returns 6. 我认为您的算法返回6。

You just need to add a loop to see if i can divide n multiple times and I think it will fix this issue. 您只需要添加一个循环,看看i可以将n除以多次,我认为它将解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM