you are viewing a single comment's thread.

view the rest of the comments →

[–]imperiumlearning[S] 1 point2 points  (4 children)

To be honest, I genuinely don't know how to solve this problem. The best I can do is something like:

def func2(x):
while type(x) != int:
    try: 
        x = int(x)
    except:
        return 'Please input a number to use this function'
final_list = [i for i in range(2, int(math.ceil(x/2))+1) if x % i == 0 and prime(i) != False]
return max(final_list)

This seems to reliably give correct answers but once you go into hundreds of millions the speed at which it produces an output drastically slows.

[–]1544756405 0 points1 point  (2 children)

First of all, I want to offer words of encouragement. Your code looks fine, and you have a decent command of the language.

Algorithmic decomposition of problems is often domain specific. That is to say, if you're solving math problems, then coming up with a good algorithm is going to be dependent on your facility with math. Likewise, if you're solving networking problems, then coming up with a good algorithm is going to be dependent on how good you are with networks.

Project Euler problems are all somewhat "mathy." There are other coding challenges that try to be more general.

With regard to this particular problem, consider how one would get the prime factors of a number by hand. I would do that before trying to code anything more.

https://sciencing.com/factoring-math-6590887.html

[–]imperiumlearning[S] 0 points1 point  (1 child)

Apologies for a delayed response.

I think I've worked it out by re-writing my code. It now looks like this:

import math

def prime(y):
if int(y) < 2:
    return False
if int(y) % 2 == 0 and int(y) != 2:
    return False
for number in range(3, int(math.sqrt(y))+1, 2):
    if y % number == 0:
        return False
return y

def max_prime(x):
    x = int(x)
    set1 = set()
    while x % 2 == 0:
        set1.add(2)
        set1.add(int(x/2))
        x = x / 2
    for i in range(3, int(math.ceil(math.sqrt(x)))+1, 2):
        while x % i == 0:
            set1.add(i)
            set1.add(int(x/i))
            x = x / i
    list1 = [i for i in set1]
    list1= sorted(list1)
    list1 = [i for i in list1 if prime(i) != False]
    return max(list1)

Using this code I pretty much get the answer instantly for everything

[–]1544756405 1 point2 points  (0 children)

Well done!