the program is not running the way I want it to be.
number = int(input('Enter a number'))
if number < 2:
print('Number cannot be less than 2')
for digits in range(2,number 1):
for a in range(digits):
if number % a ==0:
print(number)
CodePudding user response:
In the second loop, your running the range from 0 to digits which makes the first value of 'a'=0 throw us an error of zero-division.
number = int(input('Enter a number'))
if number < 2:
print('Number cannot be less than 2')
for digits in range(2,number 1):
flag = True
for a in range(2,digits):
if digits%a ==0:
flag = False
break
if(flag):
print(digits)
Here we need to use a boolean variable to know if it has satisfied the condition even once. If it does then it's not a prime number in that case we should not print the value.
This is a basic approach to solving this problem ( Time complexity - O(n^2)) we can use 2 more methods such as
- n/2 1
- sqrt(n) 1 in the second loop to reduce the complexity.
refer this link for Most Optimized Method
CodePudding user response:
You have your logic screwed up...
Remember, a number is prime if it's not divisible by any number from 2 to (n-1). So, going through a loop from 2 to n-1, if the modulo is 0, it's not a prime.
So, your first three lines are fine, assuming the spacing is corrected:
number = int(input('Enter a number'))
if number < 2:
print('Number cannot be less than 2')
You want a loop going from 2 to number--you get that with range(2, number 1). I'll call this loop i, because THAT'S THE LAW. (Just kidding, but i as a loop variable is common.)
Now we check each i with another loop going from 2 to i-1, which I'll call j. Again, if (i % j) is 0 at any point during this loop, i is not prime. Now, you could use a break statement, but just to make the code cleaner, we'll add another variable:
for i in range(2,number 1):
prime=True
j = 2
while j<i and prime:
if i%j == 0:
prime=False
else:
j = 1
if prime:
print i
Note that the while loop doesn't do anything when i=2, but that's fine since 2 is prime and gets printed. The last if ensures that for i>2, i is only printed if it went through the entire while loop without triggering if i%j == 0, which means none of the numbers are even divisors of i, which means i is prime.
Of course this isn't optimized, but it should work.