r/projecteuler • • Sep 13 '26

How can I improve my code for #3?

https://projecteuler.net/thread=3;page=8#456965

Link to my post on the forum since I don't know if I am allowed to post it on here. I don't know how I got the solution the first time since now when I run it. Nothing happens when I use 600851475143, it works fine with smaller numbers like the one they used in the example though.

Edit: It does work it just takes a long time.

1 Upvotes

4 comments sorted by

1

u/pintann Sep 13 '26 edited Sep 13 '26

For the problem specifically, take a look at the overview pdf linked from the problem

On general programming I would advise you to avoid using flags to control loop termination; instead use break, continue, return where appropriate.

Global variables in general are footgun: They allow you to causally link distant pieces of code (which is powerful!). But this prevents the reader from reasoning locally about your code. Local reasoning requires the reader to keep track of fewer things, so keep variable scopes as small as possible.

1

u/AdeptIntroduction983 Sep 13 '26

Thanks, I'll read over the PDF once I'm home. I didn't know abiut break, continue, return. How do I get a out of the function without using Globals?

1

u/pintann Sep 13 '26

Functions can return a value:

def add1(a):
    return a + 1
n = add1(41)
# n is now 42

Python is special because a function can even have multiple return values:

def div_rem(a, b):
    return a //b, a % b
q,r = div_rem(42, 8)
# q = 5, r = 2

And you could repeatedly update a and b like so:

a,b = factoring(a,b)

1

u/CowboyBoats Sep 14 '26

You're doing amazing to tackle Project Euler problems with programming as a beginner learner! Especially if you have a good background in math and want to learn programming, or even if you don't have any background in math, it's an awesome way to learn a lot of advanced concepts.

The advanced concepts are of no use if you don't know the basic concepts, though. There are many ways to learn the fundamental syntax of Python - one that I often recommend is "the Flask mega-tutorial" by Miguel Grinberg. This is more of a basic web-dev project than a math programming project, but the idea is just to get started using the tools of a software developer - not just Python but also a little bash, git for version control (git alone helped me so much with Euler because it frees you to make mistakes; you can just undo them if your code is all under version control), and other things like HTML templating that aren't at all applicable to project euler but are very helpful to know down the line.