Python While Loop To Find Prime Does Not Terminate - python

flag = 0
n = int(input('\nEnter whole number to check : '))
i = 2
while i <= (n/2):
if (n%i) == 0:
flag = 1
break
if n == 1:
print('1 is neither prime nor composite')
elif flag == 0:
print(n,' is a prime number.')
elif flag == 1:
print(n,' is not a prime number.')
Upon Entering a number >= 3, the program stalls and the cursor keeps blinking endlessly. I initially tries 277, then 13, then 5, then 3 - none of which gave a result even after a minute.
Entering 2 worked.
There must be something wrong with the code.

Your loop is not changing n or i, which are the conditions on which it stops.
I think the correct code should be:
flag = 0
n = int(input('\nEnter whole number to check : '))
i = 2
while i <= (n/2):
if (n%i) == 0:
flag = 1
break
i += 1
if n == 1:
print('1 is neither prime nor composite')
elif flag == 0:
print(n,' is a prime number.')
elif flag == 1:
print(n,' is not a prime number.')

If I understand correctly, you're trying to check if a number entered is a prime number.
This code works:
# prime numbers are greater than 1, num is the entered number
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")
At the end, you can also check for number 1 if you want.

The code below works:
flag = 0
n = int(input('\nEnter whole number to check : '))
i = 2
while i <= (n/2):
if (n%i) == 0:
flag = 1
break
else:
i += 1
if n == 1:
print('1 is neither prime nor composite')
elif flag == 0:
print(n,' is a prime number.')
elif flag == 1:
print(n,' is not a prime number.')
This is because you need to increment i by 1 after every iteration, or your while loop will run endlessly.

Related

How to use continue in while loop?

I tried to use continue in a while loop to skip print number but it doesn't work.
num = int(input())
while int(num) > 0 :
num-=1
print(num)
if num == 6:
continue
elif num ==1:
print("8 Numbers Printed Successfully.")
break
#i want to remove number six
Try this
num = int(input())
while num > 0 :
num -= 1
if num == 6:
continue
elif num == 1:
print("8 Numbers Printed Successfully.")
break
print(num)
Your print line should be after the if-else block
num = int(input())
while int(num) > 0:
num -= 1
# print(num) => if you print here, it does not check the condition
if num == 6:
continue
elif num == 1:
print("8 Numbers Printed Successfully.")
break
# print number here
print(num)
First of all, how do you know it's been 8 numbers? The input can be any number. Secondly, if you want to print every number but 6 you need to move the num -= 1 too. Being there, it won't print the first number.
Try this if you don't insist on using continue:
num = int(input())
printed_numbers = 0
while int(num) > 0 :
if num != 6:
print(num)
printed_numbers += 1
num -= 1
print("{} Numbers Printed Successfully.".format(printed_numbers))
Or this, if you want to test continue:
num = int(input())
printed_numbers = 0
while int(num) > 0 :
if num == 6:
num -= 1
continue
print(num)
printed_numbers += 1
num -= 1
print("{} Numbers Printed Successfully.".format(printed_numbers))
Finally, If you're ok with the num -= 1 there:
num = int(input())
printed_numbers = 0
while int(num) > 0 :
num -= 1
if num == 6:
continue
print(num)
printed_numbers += 1
print("{} Numbers Printed Successfully.".format(printed_numbers))
NOTE: I'm using printed_numbers because if the input is less than 6 you will print all the numbers else you'll have one less. You can use this condition instead.
You are print the number before the condition. chnage the code as follows.
num = int(input())
while int(num) > 0 :
num-=1
if num != 6:
print(num)
elif num == 1:
print("8 Numbers Printed Successfully.")
break
#i want to remove number six

How to find primes (Python)

I'm beginner in python programming and got stumpled on a Basic Question:
print the number of primes up to a given number.
For example the amount of primes before the number 100.
why my Code is not working? or what is wrong with my logic?
def count_prime(num):
newnumber = 0
for x in num:
if x%2 == 0:
newnumber = newnumber + 1
print(newnumber)
count_prime(100)
One very simple way (i.e. computationally slow) to test if a number is prime is to simply check if it can be divided by any other number.
def is_prime(n):
# If n is 0 or 1, it is not prime
if n <= 1:
return False
# Check every number between 2 and n-1
for i in range(2, n):
# If n is divisible by i, then the remainder will be zero
if n % i == 0:
return False
# Since n wasn't divisible by any other number, it must be prime
return True
To print all of the primes, you can then simply check each number.
for i in range(num):
if is_prime(i):
print(i)
This method will be very slow for large values of num. To see some much faster methods for checking the primality of a number you can have a look at this question.
num = int(input("Enter a number: "))
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")

Python - listing prime numbers from 1 to 1000 including 1

This program is for listing all the prime numbers between 1 and 1000, but my teacher would like me to include 1 in the results.
I tried to change it to say if num >= 1: and for i in range(1,num), but then when I ran it, the only result was 1 is a prime number!. Thanks!
for num in range(1,1001):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num,"is a prime number!")
You should not write for i in range(1, num):, because (any number) % 1 == 0. if num >= 1: can also be removed, because it's always true.
Try the following code:
for num in range(1, 1001):
for i in range(2, num):
if num % i == 0:
break
else:
print num, 'is a prime number'
And remember, technically speaking, 1 isn't a prime number.
Leave your code as is and above the main for loop add:
print("1 is a prime number")
a = int(input("enter the start number"))
b = int(input("enter the end number"))
for i in range(a,b+1):
if i > 1:
for j in range(2,i):
if i % j == 0:
break
else:
print(i,"is a prime number")
import math
n1 = 1000
run_lim = math.ceil(math.sqrt(n1))
prm_num = [2]
for i in range (1,n1+1) :
if i == 1 :
continue
else :
count = 0
for j in range (len(prm_num)) :
if (prm_num[j] <= run_lim) and (i%prm_num[j]) == 0 :
count += 1
if count == 0 :
prm_num.append(i)
print("The Prime Numbers are :- \n")
print(*prm_num, sep=",")
import gmpy2
c = []
for i in range(1,1000):
if gmpy2.is_prime(i)==True:
c.append(i)
print(c)

Python prime number calculator

prime = [2]
while len(prime) <= 1000:
i=3
a = 0
for number in prime:
testlist= []
testlist.append(i%number)
if 0 in testlist:
i=i+1
else:
prime.append(i)
i=i+1
print(prime[999])
Trying to make a program that computes primes for online course. This program never ends, but I can't see an infinite loop in my code.
A prime number is a number that can only be divided by exclusively one and itself.
My logic is that if a number can be divided by prime numbers preceding it then it is not prime.
As the comments to your question pointed out, there is several errors in your code.
Here is a version of your code working fine.
prime = [2]
i = 3
while len(prime) <= 1000:
testlist = []
for number in prime:
testlist.append(i % number)
if 0 not in testlist:
prime.append(i)
i = i + 1
print prime
I haven't tested but you can create method like below:
def get_prime_no_upto(number):
start = 2
primes = list(range(start,number)).to_a
for no in range(start,number):
for num in range(start,no):
if ( no % num == 0) and (num != no):
primes.delete(no)
break
primes
and can use it like
print primeno(100)
cheers!
def prime_checker(number):
stop = False
prime = True
n = 2
while stop == False and n < number:
if (number) % n == 0:
prime = False
stop = True
n += 1
if prime == True:
print("It's a prime number.")
elif prime == False:
print("It's not a prime number.")
prime_checker(11)

To find the 9th Fibonacci Prime number

I'm not sure if this is the right place to ask but I have run into a wall, code-wise. I am trying to find the 9th Fibonacci number which is a Prime number but am having problems. First, my function to check if the number is Prime returns None for single digit prime numbers (2,3,5,7). Next, I think the value I'm looking for is 514229 as shown here but my program shows gives me the value 17711 as the 9th Fibonacci prime which is incorrect. My code is posted below:
def isPrime(n):
n = abs(int(n))
if n < 2:
return False
elif n == 2:
return True
elif not n & 1:
return False
else:
for x in range(3, n/2):
if n % x == 0:
return False
return True
def chkFibonacci():
num1 = 1
num2 = 1
mySum = 0
ctr = 0
choice = 'n'
while (choice != 'y'):
mySum = num1+num2
#print mySum
if (isPrime(mySum)== True):
ctr = ctr + 1
print mySum
if (ctr == 9):
print mySum
break
num1 = num2
num2 = mySum
chkFibonacci()
print isPrime(3)
Any help is appreciated. Thanks in advance!!
return True in the else branch of isPrime seems to be indented too much.

Categories

Resources