Project Euler #3 takes forever in Java

后端 未结 9 836
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-04 03:01

Problem #3 on Project Euler is:

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 60085147514

9条回答
  •  孤街浪徒
    2020-12-04 03:07

    public HashSet distinctPrimeFactors(int n) //insane fast prime factor generator
    {
        HashSet factors = new HashSet();
        int lastres = n;
        if (n==1)
        {
            factors.add(1);
            return factors;
        }
        while (true)
        {
            if (lastres==1)
                break;
            int c = 2;
            while (true)
            {
                if (lastres%c==0)
                    break;
                c++;
            }
            factors.add(c);
            lastres/=c;
        }
        return factors;
    }
    

    If you want to generate distinct prime factors for a number quickly use this method which makes the number smaller on each iteration. You can change int to long and it should work for you.

提交回复
热议问题