Home > Enterprise >  Program to find a specific prime number end in an infinite loop
Program to find a specific prime number end in an infinite loop

Time:09-22

Hey guys i have a problem i wrote this code for projecteuler to find a specific prime number but it in ends in an infinite loop i looked it up and found many alternatives but want to understand why this code just dosent work. Im new to programing so if you also have any tipps to improve my code i will appreciate them.

import math

x = 1   #number that is getting checked
y = 0   #indicator of how many prime numbers found
a = 0   #the most recent prime number
while y < 6:    
    for i in range (2, int(math.sqrt(x))):
        if (x % i ) == 0:
            x = x   1
            break
        else:
            a = x
            x = x   1
            y = y   1
        break
print (a)

CodePudding user response:

You put x = 1, and then loop on a range starting from 2: so the for is never executed, and the while loops indefinitely. You need to start with x = 2, or to handle the special case of x = 1

EDIT The code works for x at least 9: the for loop is never executed until int(math.sqrt(x)) is at least 3

  • Related