Prime Numbers python

前端 未结 5 888
长情又很酷
长情又很酷 2021-01-18 19:34

I\'m a beginning programmer in python and have a question about my code I\'m writing:

number = int(input(\"Enter a random number: \"))

for num in range(1, n         


        
5条回答
  •  暖寄归人
    2021-01-18 19:56

    Your problem

    The else statement that you put inside the for loop means that if that number(num) is divisible by this current no represented by i, return true considering it as a prime which IS NOT CORRECT.

    Suggestion

    Your outer loop starts with 1 which should change to 2, as 1 is not a prime number

    Solution

    def fun(number):
     #Not counting 1 in the sequence as its not prime
     for num in range(2, number + 1) :
        isPrime = True
        for i in range(2, num) :
             if (num % i) == 0 :
            isPrime = False  
                break
        if isPrime:
            print num
    fun(10) 
    

    Output

    1

    2

    3

    5

    7

提交回复
热议问题