Home > other >  How to correct this nested for-loop in my python program
How to correct this nested for-loop in my python program

Time:11-30

I wrote this program to find n amount of prime numbers from 2 up to a user-specified integer but it isn't preforming how I wanted. I'm not sure if it is the nested loop or the way I am formatting the output that is giving me the issues. Expected outcome is below.

def is_prime(user_number):       #Find all prime numbers from 2 and up to the user entered integer and store them in a list. 
    primes = []
    for num in range(2,user_number):
    
        for x in range(2,num):
            if num % x == 0:
                break
        else:
            primes.append(num)
    return primes


def format_primes(primes_list):
    printed_primes = []
    for sequence, primes in enumerate(primes_list, start=1):
        printed_primes = print(f"Prime # {sequence} = {primes}")
    return printed_primes

def main():
    user_number = get_user_num()
    list_of_primes = is_prime(user_number)
    output_of_primes_list = format_primes(list_of_primes)
    #print(list_of_primes) 

Here is the output for an input of 100...

Prime # 1 = 2
Prime # 2 = 3
Prime # 3 = 5
Prime # 4 = 7
Prime # 5 = 11
Prime # 6 = 13
Prime # 7 = 17
Prime # 8 = 19
Prime # 9 = 23
Prime # 10 = 29
Prime # 11 = 31
Prime # 12 = 37
Prime # 13 = 41
Prime # 14 = 43
Prime # 15 = 47
Prime # 16 = 53
Prime # 17 = 59
Prime # 18 = 61
Prime # 19 = 67
Prime # 20 = 71
Prime # 21 = 73
Prime # 22 = 79
Prime # 23 = 83
Prime # 24 = 89
Prime # 25 = 97

The formatting is how I want it, but the first number should go to 100, not 25. The program is only finding primes up to 100, but the 100th prime should be 541,

Here is an example of what I need:

Prime # 100 = 541

Thanks for any help you can give me!

CodePudding user response:

In this case, you should use a while loop. Stop until the number of prime numbers reaches user_number.

Moreover, prime checking can be improved as mentioned in comment.

def is_prime(user_number): 
    primes = []
    count = 0
    num = 2
    while count < user_number:
        # checking 2 to sqrt(num) is enough
        for x in range(2, int(math.sqrt(num))   1):
            if num % x == 0:
                break
        else:
            primes.append(num)
            count  = 1
        num  = 1
    return primes
  • Related