Euler problem number #4

前端 未结 14 2027
萌比男神i
萌比男神i 2021-01-03 11:00

Using Python, I am trying to solve problem #4 of the Project Euler problems. Can someone please tell me what I am doing incorrectly? The problem is to Find the larg

14条回答
  •  星月不相逢
    2021-01-03 11:35

    The question states:

    What is the largest prime factor of the number 600851475143?
    

    I solved this using C#, but the algorithm itself is language-agnostic.

    1. Create a method for determining if a number is prime or not. This can be brute-force (rather than using a much more efficient sieving algorithm) and looks like this:

    private static long IsPrime(long input)
            {
                if ((input % 2) == 0)
                {
                    return 2;
                }
                else if ((input == 1))
                {
                    return 1;
                }
                else
                {
                    long threshold = (Convert.ToInt64(Math.Sqrt(input)));
                    long tryDivide = 3;
                    while (tryDivide < threshold)
                    {
                        if ((input % tryDivide) == 0)
                        {
                            Console.WriteLine("Found a factor: " + tryDivide);
                            return tryDivide;
                        }
                        tryDivide += 2;
                    }
                    Console.WriteLine("Found a factor: " + input);
                    return -1;
                }
            }
    
    1. Once I have a function to determine primality, I can use this function to find the highest prime factor

    private static long HighestPrimeFactor(long input)
    {
        bool searching = true;
        long highestFactor = 0;
        while (searching)
        {
            long factor = IsPrime(input);
            if (factor != -1)
            {
                theFactors.Add(factor);
                input = input / factor; 
            }
            if (factor == -1)
            {
                theFactors.Add(input);
                highestFactor = theFactors.Max();
                searching = false;
            }
        }
        return highestFactor;
    }
    

    I hope this helps without giving too much away.

提交回复
热议问题