Checking Odd Perfect Square as Prime Number in Python [duplicate] - python

This question already has answers here:
Prime numbers multiplied by 3 shown as prime numbers
(3 answers)
Closed 9 months ago.
I have tried this very basic code for checking prime numbers in python and it is working fine until you enter odd perfect squares like 9, 25, 121 etc. It results in saying that these are prime numbers. So what is the issue?
def isPrime(a):
nums = range(2,a)
for num in nums:
if (a % num) == 0:
return False
else:
return True
print('Enter an integer to check if it is prime')
a = input()
a = int(a)
if isPrime(a):
print('The number is prime')
else:
print('The number is not prime')

You can use %2 sign to determine.
Only 2 and 1 does not fit the criteria and thus need to have their own specific function since 2 is a prime number and 1 is not a prime number.
a = input("Input number: ")
a = int(a)
if a == 2:
print('The number is prime')
elif a ==1:
print("The number is not prime")
elif a%2 == 0:
print("The numbr is not prime")
else:
print('The number is prime')

Related

add to list (identifying whether input is a prime number)

Trying to write a function 'prime_check(number)' to test if an argument is a prime number
The number_of_factors for a given number should only be 1 (the given number itself) and '1', which is already excluded in the while statement
Having trouble adding a variable to the list "set_of_factors"
Tried to debug in Thonny, which says that set_of_factors = none
def prime_checker(number):
set_of_factors=[]
number_of_factors=len(set_of_factors)
f=2
while number > 1 and f<=number:
if number%f == 0:
set_of_factors.insert(0,1)
f+=1
else:
f+=1
if number_of_factors==1:
print("It is a prime number")
else:
print("It is not a prime number")
n = int(input("Check this number: "))
prime_checker(number=n)
Prime numbers have two factors, one and itself. Ex. 5's factors would be (1, 5)
Also istead if ".insert" use ".append"
def prime_checker(number):
set_of_factors=[]
number_of_factors=len(set_of_factors)
f=2
while number > 1 and f<=number:
if number%f == 0:
set_of_factors.insert(0)
f+=1
else:
f+=1
if number_of_factors==2:
print("It is a prime number")
else:
print("It is not a prime number")

Why shouldn't I put the "else" same level with "if" in Python

When I put else the same level with if, the program didn't work when i called my function. (little star in jupyter notebook). But when I pulled "else" one level behind, everything was ok. The function is meant to return the number of prime numbers that exist up to and including a given number. Here is my code :
def count_primes(num):
primes = list(range (3,num,2))
digit = 3
if num < 2:
return 0
while digit <= num:
for x in range (3, digit, 2):
if digit % x == 0:
primes.remove(digit)
digit += 2
break
else:
digit += 2
primes.insert(0,2)
print (primes)
return len(primes)
It is because you do not want to get the else in the for loop. You just need to return the prime numbers once.
For example if I make the program just to check whether a number is prime or not -
if num > 1:
# check for factors
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")if num > 1:
# check for factors
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")
PS: I have not included if the number is one or less.
I do not want to print Number is not prime several times. Because if I put else inside the loop, it will run every time if fails.

How do you find the first N prime numbers in python?

I am pretty new to python, so I don't fully understand how to use loops. I am currently working on a piece of code that I have to find the first N prime numbers.
The result that is desired is if you input 5, it outputs 2, 3, 5, 7, and 11, but no matter what I input for 'max', the output always ends up being 2 and 3. Is there a way to improve this?
max=int(input("How many prime numbers do you want: "))
min=2
while(min<=(max)):
for c in range(2, min):
if min%c==0:
break
else:
print min
min=min+1
You only increment min in the else block, i.e., if min % c is nonzero for all c, i.e., if min is prime. This means that the code won't be able to move past any composite numbers. You can fix this by unindenting min=min+1 one level so that it lines up with the for and else.
number = int(input("Prime numbers between 2 and "))
for num in range(2,number + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
Solution: Get the nth prime number entry. Iterate through each natural numbers for prime number and append the prime number to a list. Terminate the program when length of a list satisfies the user nth prime number entry.
# Get the number of prime numbers entry.
try:
enterNumber = int(input("List of nth prime numbers: "))
except:
print("The entry MUST be an integer.")
exit()
startNumber = 1
primeList = []
while True:
# Check for the entry to greater than zero.
if enterNumber <= 0:
print("The entry MUST be greater than zero.")
break
# Check each number from 1 for prime unless prime number entry is satisfied.
if startNumber > 1:
for i in range(2,startNumber):
if (startNumber % i) == 0:
break
else:
primeList.append(startNumber)
if (len(primeList) == enterNumber):
print(primeList)
break
else:
startNumber = startNumber + 1
continue
Try that :
n = int(input("First N prime number, N ? "))
p = [2]
c = 2
while len(p) < n:
j = 0
c += 1
while j < len(p):
if c % p[j] == 0:
break
elif j == len(p) - 1:
p.append(c)
j += 1
print(p)
Its simple. Check the below code, am sure it works!
N = int(input('Enter the number: ')
i=1
count=0
while(count<N):
for x in range(i,i+1):
c=0
for y in range(1,x+1):
if(x%y==0):
c=c+1
if(c==2):
print(x)
count=count+1
i=i+1
The following code will give you prime numbers between 3 to N, where N is the input from user:
number = int(input("Prime numbers between 2, 3 and "))
for i in range(2,number):
for j in range(2,int(i/2)+1):
if i%j==0:
break
elif j==int(i/2):
print(i)
You can see to check a number i to be prime you only have to check its divisibility with numbers till n/2.

Python - Prime check and increment

My objective of the below code is
check if entered number is a prime
if not print the next biggest prime
def primetest (num):
for c in range (2, num):
if num % c == 0:
repeattest (num) #not prime? increment number
else :
print (num,"is a prime number")
break
def repeattest (num): # check prime if not increment number by 1
for z in range (2, num):
num = num+1
primetest (num)
if num % z == 0:
num = num+1
else:
print ("Next Prime:", num+1)
break
num = int (input ("enter a number:")) # main code:
for y in range (2, num):
if num % y == 0:
repeattest (num)
else:
print (num,"is a prime number")
break
I think the logic is fine, but not sure why im not getting any output.
Time comlexity of your code is O(N) when it find a number which is prime or not.
There is no pointing on dividing from 2 to len(num)-1. It is enough to loop from 2 to sqrt of the given number. Therefore time complexity reduce to O(n) to O(log(n)).
import math
num = int (input ("enter a number:"))
def primeTest(num):
isPrime = 0
for i in range(2,int(math.sqrt(num)+1)):
if num%i == 0:
isPrime = isPrime + 1
break
if isPrime == 0:
print(num, "is a prime number")
else:
num = num + 1
repeatTest(num)
def repeatTest (num):
isPrime = 0
for i in range(2,int(math.sqrt(num))):
if num%i == 0:
isPrime = isPrime + 1
break
if isPrime == 0:
print("Next Prime: ", num)
else:
num = num + 1
repeatTest(num)
primeTest(num)
The logic which you are using to find if a number if prime seems wrong .
Taking a integer like 9 prints "9 is a prime number" .
And also you are checking for next prime numbers from 2 to Num .
Num being the input , you cant get a number greater than that .
It exits from the loop without even getting in , therefore not printing anything when you are searching for next prime .
You need to change the logic .
write a separate function for checking prime and end the loop when you find the next prime number instead of stopping at num .

Coding exclusions in a for loop (python) [duplicate]

This question already has answers here:
Sieve of Eratosthenes in Python
(3 answers)
Closed 6 years ago.
i'm trying to figure out how to exclude certain numbers (numbers that aren't prime) in my program. For example, I don't want 15 to be printed so I used the modulo to exclude numbers divisible by 5 but that eliminates 5, which is a prime number. Any help on how to code this would be huge help! Thank you...
start = int(input("Start number: "))
end = int(input("End number: "))
while start < 0 or end < 0:
print ("Start and end number must be positive. Try again.")
start = int(input("Start number: "))
end = int(input("End number: "))
while start > end:
print ("End number must be greater than start number. Try again.")
for x in range (start, end):
is_prime = True
for x in range (start, end):
trial = x % 2
trial1 = x % 5
trial2 = x % 3
if trial != 0 and trial1 != 0 and trial2 != 0:
print (x, "is a prime number")
x = x + 1
else:
is_prime = False
You can create a list of numbers you want to use in your loop let's call it loop_list and then simply use for x in loop_list, that avoid you setting up exclusions
If you want to be sure that N is a prime number, you have to check for all number to squareroot(N) if N%number != 0.
Are you looking for optimisation? If no, you just need that.
You can try this prime number logic :-
def check_prime(num):
notPrimeFlag = 'N'
for i in range(2, num):
if num % i == 0:
notPrimeFlag = 'Y'
break
if notPrimeFlag == 'N':
print("Prime number")

Categories