Python Prime Number - python

I just started learning python. I'm trying to write a program that prints prime no. but it also printing no. ending with 5.
n = 2
while n >= 2:
if n == 2:
print(n)
n += 1
while n >= 3:
if n == 3:
print(n)
n += 2
for i in range (3,n):
if n % i != 0:
print(n)
n += 2

Here is an algorithm for deciding primes:
def prime(iterations):
primes = [2]
x = math.floor(math.sqrt(iterations)) + 1
for i in range(iterations):
if i > 2:
primes.append(i)
for i in range(x):
if i > 1:
j=2
while i*j <= iterations:
if i*j in primes:
primes.remove(i*j)
j += 1
print(primes)
explanations:
line 4: appends every num to primes
line 7 and line 3: finds numbers between 1 and iterations and removes all possible factors
line 13: cycling through factors

You can use below code for finding prime number.
num = int(input("Enter 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")
else:
print(num, " is not a prime number")
prime number always greater than 1 so you have check for it also.

x=int(input("Give your No: "))
for k in range(2,x):
if ((x%k)==0):
print('Not prime no')
break
else:
print("Prime no")

Related

How to count sum of prime numbers without a number 3?

I have to count the sum of all prime numbers that are less than 1000 and do not contain the digit 3.
My code:
def primes_sum(lower, upper):
total = 0
for num in range(lower, upper + 1):
if not num % 3 and num % 10:
continue
elif num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
total += num
return total
total_value = primes_sum(0, 1000)
print(total_value)
But still I don't have right result
def primes_sum(lower, upper):
"""Assume upper>=lower>2"""
primes = [2]
answer = 2
for num in range(lower, upper+1):
if any(num%p==0 for p in primes): continue # not a prime
primes.append(num)
if '3' in str(num): continue
answer += num
return answer
The issue in your code was that you were checking for num%3, which checks whether num is divisible by 3, not whether it contains a 3.

Is there a way to print at which point for loops ended?

I have a little thing here which checks if a number is prime or not:
num = int(input("Choose a number: "))
for i in range(2, num):
if num % i == 0:
print("Not prime")
break
else: print("prime")
What I would like to add is the output on which number the foor loop ended, so which number is the smallest divisor of num
Example: for num = 8 it would be 2. For num = 21 it would be 3
How can I implement that?
you can try this:
for i in range(2, num):
if num % i == 0:
print(num, " is Not prime")
print("Smallest devisor of num is = ", i)
break
else:
print("prime")

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 .

Prime Numbers python

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, number + 1) :
for i in range(2, num) :
if (num % i) == 0 :
break
else :
print(num)
break
When I run this program I also get 9, 15 21 as output. But these are not prime numbers.
What is wrong with my code?
Thanks!
With if (num % i) == 0: you go to the else block for every num, which is not a multiply of 2, as you start i with 2, thus printing num. I got all odd numbers printed with your code.
You can use something like this:
number = int(input("Enter a random number: "))
for num in range(1, number + 1):
prime = True
for i in range(2, num):
if (num % i) == 0:
prime = False
break
if prime:
print(num)
It sets prime to False when it encounters a divisor without rest.
the trouble is in your else: statement which has to run outside of the first loop. I recommend the following:
def isprime(num):
for i in range(2, num):
if (num % i) == 0:
return False
return True
for num in range(1, number + 1) :
if isprime(num):
print num
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
I am assuming the random number is the range you want the numbers to be within.
I found that the variable i is always equal to 2 in your code.This destroys the purpose of having a second for loop
Prime numbers are numbers that cannot be divisible by 2, 3 or 7, excluding 2, 3 or 7!
With this knowledge I adapted your code to show the true prime numbers.
solution
number = int(input("Enter a random number: "))
for num in range(2,number +1) :
printnum = True
if num == 2:
printnum = True
elif num == 3:
printnum = True
elif num == 7:
printnum = True
elif num % 2 == 0:
printnum = False
elif num % 3 == 0:
printnum = False
elif num % 7 == 0:
printnum = False
if printnum == True:
print(num)
This is my method to generate first ten prime numbers with no imports, just simple code with components we are learning on college. I save those numbers into list.
def main():
listaPrim = []
broj = 0
while len(listaPrim) != 10:
broj+= 1
brojac = 0
for i in range(1,100):
if broj % i == 0:
brojac += 1
if brojac == 2:
listaPrim.append(broj)
print(listaPrim)
if __name__=='__main__':
main()

Categories