Prime Numbers python - 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()

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.

Why does using for loop for finding prime number runs only runs once?

I want to find the prime numbers up to the given number but my loop only runs once and my output is only 2 and 3, where did I went wrong?
def primer_check(n):
prime_state = True
for i in range(2,n+1):
if i == 2:
print(2)
continue
for j in range(2,i):
if i % j == 0:
prime_state = False
break
if prime_state: print(i)
n = int(input("Enter a number to see the prime numbers up to that number : "))
primer_check(n)
you have to set prime_state to True everytime when you start a new loop.here is the code.you are almost correct .Hope it helps :)
def primer_check(n):
for i in range(2,n+1):
prime_state = True
if i == 2:
print(2)
continue
for j in range(2,i):
if i % j == 0:
prime_state = False
break
if prime_state: print(i)
n = int(input("Enter a number to see the prime numbers up to that number : "))
primer_check(n)

Python prime number finder doesn't work (using break command)

I'm trying to make a relatively efficient piece of Python code that will sum all the primes under 2 million, but this code doesn't seem to work. It regards numbers like 9 and 15 prime for some reason:
sum = 2
for num in range(3, 2000000, 2):
for i in range(2, 1+int(num**0.5)):
if num % i == 0:
break
sum += num
print(sum)
As written, your code ignores the checks in the inner for loop, and sums the current number regardless of whether or not it's a prime or not.
Either use a flag variable:
prime_sum = 2
for num in range(3, 2000000, 2):
is_prime = True
for i in range(2, 1+int(num**0.5)):
if num % i == 0:
is_prime = False
break
if is_prime:
prime_sum += num
print(prime_sum)
or use the for loop's else clause (which only runs after the loop runs to completion - ie. no break):
prime_sum = 2
for num in range(3, 2000000, 2):
for i in range(2, 1+int(num**0.5)):
if num % i == 0:
break
else:
prime_sum += num
print(prime_sum)
You're not checking whether the inner loop found a factor or not before adding num to sum.
You can use the else: block of a loop to tell whether the loop finished or stopped due to break.
sum = 2
for num in range(3, 2000000, 2):
for i in range(2, 1+int(num**0.5)):
if num % i == 0:
break
else:
sum += num
print(sum)
You're breaking out of the inner loop if the number is not prime, but then are still executing the line
sum += num
There are multiple solutions to this.
Moving the primality test to a function
def is_prime(x):
for i in range(2, int(x ** 0.5) + 1):
if x % i == 0:
return False
return True
sum = 2
for num in range(3, 2000000, 2):
if is_prime(num):
sum += num
print(sum)
is_prime variable
sum = 2
for num in range(3, 2000000, 2):
is_prime = True
for i in range(2, 1+int(num**0.5)):
if num % i == 0:
is_prime = False
break
if is_prime:
sum += num
print(sum)
all() and a list comprehension
sum = 2
for num in range(3, 2000000, 2):
if all([num % i != 0 for i in range(int(x ** 0.5) + 1)]):
sum += num
print(sum)

Python3.x Prime Number List with while loop

def prime(upper):
while upper >=2:
for num in range(2, upper + 1):
prime = True
for i in range(2, num):
if (num % i == 0):
prime = False
if prime:
print(num, end=",")
if num == upper: #I think there is a problem here
break
prime(7)
How can I stop this function when it reachs 7 value
PS: I want to execute this codes with while loop.
BTW if you can make it this codes without for-loop please do it for me :)
I appreciate you...
EDIT:
I guess my previous is_prime function is problematic. This way is quicker and works well:(Source)
def is_prime(n):
""""pre-condition: n is a nonnegative integer
post-condition: return True if n is prime and False otherwise."""
if n < 2:
return False;
if n % 2 == 0:
return n == 2 # return False
k = 3
while k*k <= n:
if n % k == 0:
return False
k += 2
return True
You should use this function.
BEFORE EDIT:
I would use the is_prime function from here. You can use another way.
And, I would suggest this code for you:
def is_prime(Number):
return 2 in [Number, 2**Number%Number]
def prime(upper):
print([num for num in range(2, upper + 1) if is_prime(num)])
prime(7)
Output:
[2, 3, 5, 7]
But if you insist on using only while loop, you can modify your prime function as:
def prime(upper):
num = 2
while num <= upper:
if is_prime(num):
print(num, end = ",")
num += 1
Then, output will be:
2,3,5,7,

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 .

Categories