Prime Numbers in Java - Algorithms

前端 未结 6 891
南笙
南笙 2021-01-22 15:48

I have started learning to code in Java and decided I would use the Project Euler site to give me little tasks to try and complete with each bit of new coding I learn. So I came

6条回答
  •  清歌不尽
    2021-01-22 16:42

    A simple algorithm for factoring a composite number by trial division goes like this:

    function factors(n)
        f, fs := 2, []
        while f * f <= n
            while n % f == 0
                fs.append(f)
                n := n / f
            f := f + 1
        if n > 1
            fs.append(n)
        return fs
    

    That algorithm can be improved, and there are better algorithms for factoring large numbers, but it's sufficient for your task. When you are ready for more, I modestly recommend the essay Programming with Prime Numbers at my blog, which includes implementations of that algorithm and others in Java.

提交回复
热议问题