Search code examples
pythonvariablesstorecomposite

How do I find the longest series of composite numbers below 10000? How do I only print the longest serie?


This is my code:

series = 0

for counter in range (1, 30):
    if counter > 1:
        for i in range (2, counter):
            if (counter % i) == 0:
                series += 1
                break
        else:
            print ("The longest series of composite numbers under 10.000 starts at %d and ends at %d the series is %d long" % ((counter-series), counter, series))
            series = 0

I would like it to give only the longest series to print, I think I need to store the variable series somewhere and check each iteration if the new value of series is higher then the previous, and swap if it is higher, and then just print once. But I can't figure out how to effectively store and swap.

Hope this is clear enough


Solution

  • I used a for else loop and it worked, this is my code in the end:

    series = 0
    b = 0 
    a = 0
    
    for num in range (1, 10000):
        for j in range (2, num):
            if (num % j) == 0:
                series += 1
                break 
    
        else:
            if series > b:
                b = series
                a = num 
                series = 0
            else: 
                series = 0
    print ("De langste reeks niet-priemgetallen onder de 10.000 begint op %d en eindigt op %d" % (((a-b), a-1)))   
    print ("de reeks is %d lang" % b)