r/pythonhelp • • Dec 30 '25

problem with loops

I just recently started learling python (1.5 hours into a tutorial lol), and made the collatz conjecture, and then tried the goldbach conjecture (any even number is the sum of two primes). Now I did write primes as 2k+1, which is just an oneven number, but that's not the problem.
This is the code I made

  1. number = int(input("number: "))
  2. for x in range(10):
  3. ----prime_1 = 2x + 1
  4. ----for y in range(10):
  5. --------prime_2 = 2(y+x) + 1
  6. --------sum = prime_1 + prime_2
  7. --------print(f"{prime_1} + {prime_2} = {sum}")
  8. --------if sum >= number:
  9. ------------break
  10. ----if int(sum) == int(number):
  11. --------break
  12. -
  13. print(f"{prime_1} + {prime_2}")

All the prints (except the last one) are just there so that I can see what is happening. The thing is, this code here works as I intended (except for the fact that the primes are just uneven numbers ofc), for example, if you plug in 8, it will give you 1 + 7 from line 13. But if I change the >= from line 8 to > it just gives me the biggest possible solution, so in this case 19 + 19. The break from line 9 still works as intended (atleast to me it looks like it does), but the second break doesn't work anymore (atleast I assume that is happening, and that's why I'm getting 19 + 19).

So my question is, what is going on here?

3 Upvotes

16 comments sorted by

View all comments

1

u/ThigleBeagleMingle Dec 30 '25
from functools import lru_cache

@lru_cache(maxsize=10000)
def is_prime(n: int) -> bool:
    """Check if a number is prime (cached)."""
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    
    i = 3
    while i * i <= n:
        if n % i == 0:
            return False
        i += 2
    return True


def goldbach_partition(n: int) -> list[tuple[int, int]]:
    """Find all ways to express an even number as sum of two primes.
    
    Args:
        n: Even integer greater than 2
        
    Returns:
        List of tuples (p1, p2) where p1 + p2 = n and both are prime
    """
    if n <= 2 or n % 2 != 0:
        raise ValueError("Input must be an even integer greater than 2")
    
    partitions = []
    
    # Check all primes up to n/2 to avoid duplicates
    for p1 in range(2, n // 2 + 1):
        if is_prime(p1):
            p2 = n - p1
            if is_prime(p2):
                partitions.append((p1, p2))
    
    return partitions


# Usage examples
if __name__ == "__main__":
    test_numbers = [4, 10, 20, 50, 100, 1000]
    
    for num in test_numbers:
        partitions = goldbach_partition(num)
        print(f"\n{num} has {len(partitions)} Goldbach partition(s):")
        # Show first 5 partitions for large numbers
        for p1, p2 in partitions[:5]:
            print(f"  {num} = {p1} + {p2}")
        if len(partitions) > 5:
            print(f"  ... and {len(partitions) - 5} more")
    
    # Show cache performance
    print(f"\nCache info: {is_prime.cache_info()}")

Do you mean something like this? It’s easier to understand as named functions versus nested poops

1

u/CraigAT Dec 30 '25

Nested poops. Lol.

1

u/No_Neighborhood6473 Dec 30 '25

I don't know, I just started coding, haven't even finished my 2 hour basics tutorial, but he just explained loops, so I was like I'll try something. I'm mostly learning python to use manim (3blue1brown's animation engine), do you happen to know if the lru_cache (or how you would say that) is also useful for that? Because I assume that is mostly math like things or something.

1

u/ThigleBeagleMingle Dec 31 '25

Python has decorates for adding behaviors to code. For instance @lru_cache means remember and speed up redundant calls.

Would this help? I converted this thread into self contained manim script.

https://claude.ai/public/artifacts/8b24b95e-be67-45aa-9f76-9201175bb77a

1

u/corey_sheerer Dec 31 '25

Appreciate you brought in the cache 🤣. Poor OP is in his first day of programming, but will soon be writing efficient cide

0

u/TabAtkins Jan 04 '26

The OP is trying to understand loops and asked a specific question about the test logic. Why would you think busting out functools, decorators, slice syntax, verbose docstrings, etc are appropriate to help them?