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)
Related
I have to print nth prime palindrome number with the help of this program, where n is number given by the user but I have a problem in this program, as it is taking much time to print the answer.
n=int(input())
l=[]
for i in range(1,1000000):
y=True
if str(i)==str(i)[::-1]:
if i>=2:
for j in range(2,i):
if i%j==0:
y=False
break
if y:
l.append(i)
print("Your Prime Palindrome Number Is:",l[n-1])
How can I make this code time efficient?
The first part of this code is not specific to this question. It's a general purpose strategy for testing prime numbers. It's faster than sympy.isprime() for values lower than ~500,000 (Python 3.11.1 on Intel Xeon) after which the sympy version betters this implementation.
from math import sqrt, floor
def isprime(n):
if n < 2:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
for i in range(5, floor(sqrt(n))+1, 6):
if n % i == 0 or n % (i + 2) == 0:
return False
return True
Now you need something to test for a palindrome. This function will return True if the string representation of the object is palindromic.
def ispalindrome(o):
return (_ := str(o)) == _[::-1]
And this is the main part of the program. As 2 is the only even prime number, let's treat that as a special case. Otherwise start with 3 and just test subsequent odd numbers.
N = int(input('Enter value for N: '))
if N > 0:
if N == 1:
print(2)
else:
p = 3
while True:
if isprime(p) and ispalindrome(p):
if (N := N - 1) == 1:
print(p)
break
p += 2
Sample output:
Enter value for N: 11
313
Hello dearest community,
I'm stuck on something very easy, I guess sometimes your just out of it. Anyhow, I wrote this to check for prime numbers:
num = int(input(""))
if num > 1:
for i in range(2, num-1):
if (num % i) == 0:
print(num, "is no Primenumber")
break
else:
print(i, "PRIME!!!")
(The original code doesn't print anything, but I had trouble with it, so I rewrote it for debugging purposes)
Anyway, it correctly identifies non prime numbers, but prints out this for prime numbers, lets say 7:
7
2 PRIME!!!
3 PRIME!!!
4 PRIME!!!
5 PRIME!!!
Use the below logic to find the number is prime or not. This is suited for python, as there is an else block for the for loop which gets exectued when the loop is not broken during execution which mean the number is prime.
if num > 1:
# Iterate from 2 to n / 2
for i in range(2, num//2):
# If num is divisible by any number between
# 2 and n / 2, it is not prime
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")
Not the most performance conscious, but will get the job done and is simple.
n = input("Enter a number to check if it is prime [returns True or False]: ")
n = int(n)
if n < 2:
quit()
if all(n % i for i in range(2, n)):
print(n, "PRIME!!!")
If you are concerned with performance for larger numbers it is better to use square root over number flooring division 2. Any number that is a factor greater than the square root will also have 1 that is less.
Here's a common solution:
def check_for_prime(p_in):
is_prime = True
for n in range(2, int(p_in ** 0.5) + 1):
if p_in % n == 0:
is_prime = False
break
return is_prime
num = int(input(""))
if check_for_prime(num):
print(f'{num} is prime')
else:
print(f'{num} is not prime')
Without third-party module, you can easily perform it this way:
def is_prime(number):
return all(number % n for n in range(2, number))
This way, you check:
all division between the specified number, and any number between 2 and the one before the number
the trick is to consider the fact that if any number % n gives 0, which means it is a multiple, so it can't be a prime number, and you will get a result immediately
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")
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)
I need to write a code that will find all prime numbers in a range of numbers and then list them in order saying which are prime and which are not, and also if they are not prime, show by what numbers they are divisible. It should look something like this:
>>> Prime(1,10)
1 is not a prime number
2 is a prime number
3 is a prime number
4 is divisible by 2
5 is a prime number
6 is divisible by 2, 3
7 is a prime number
8 is divisible by 2, 4
9 is divisible by 3
so far I have this which will only identify what numbers are prime and print them in a list. I don't know how to do the non prime numbers and to print what numbers it is divisible by. Also I get that 1 is a prime number.
def primeNum(num1, num2):
for num in range(num1,num2):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
print (num,'is a prime number')
Using a sieve will do the trick:
Example:
from __future__ import print_function
def primes():
"""Prime Number Generator
Generator an infinite sequence of primes
http://stackoverflow.com/questions/567222/simple-prime-generator-in-python
"""
# Maps composites to primes witnessing their compositeness.
# This is memory efficient, as the sieve is not "run forward"
# indefinitely, but only as long as required by the current
# number being tested.
#
D = {}
# The running integer that's checked for primeness
q = 2
while True:
if q not in D:
# q is a new prime.
# Yield it and mark its first multiple that isn't
# already marked in previous iterations
#
yield q
D[q * q] = [q]
else:
# q is composite. D[q] is the list of primes that
# divide it. Since we've reached q, we no longer
# need it in the map, but we'll mark the next
# multiples of its witnesses to prepare for larger
# numbers
#
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1
def factors(n):
yield 1
i = 2
limit = n**0.5
while i <= limit:
if n % i == 0:
yield i
n = n / i
limit = n**0.5
else:
i += 1
if n > 1:
yield n
def primerange(start, stop):
pg = primes()
p = next(pg)
for i in xrange(start, stop):
while p < i:
p = next(pg)
if p == i:
print("{0} is prime".format(i))
else:
print("{0} is not prime and has factors: {1}".format(i, ", ".join(map(str, set(factors(i))))))
Output:
>>> primerange(1, 10)
1 is not prime and has factors: 1
2 is prime
3 is prime
4 is not prime and has factors: 1, 2
5 is prime
6 is not prime and has factors: 1, 2, 3
7 is prime
8 is not prime and has factors: 1, 2
9 is not prime and has factors: 1, 3
Just add a print and a break at the position where you set prime to false.
A more elegant solution would be to make a separate function isPrime or to use break and else in the inner for loop. Either way would make prime unnecessary.
You can only divide one by one and itself so it is a prime number, by that definition at least.
you could store the divisors for each number on a list and then print it with ", ".join(yourList)
i.e:
def primeNum(num1, num2):
for num in range(num1,num2):
divisors = []
for i in range(2,num):
if (num%i == 0):
divisors.append(str(i))
if divisors:
print ('%d is divisible by ' %num + ', '.join(divisors))
else:
print ('%d is a prime number' %num)
Edit: dumb syntax error
> # Check a number whether prime or not
a = int(input("Please your number (>1): "))
y = 2
import math
b = math.floor(math.sqrt(a)) + 1
x = True
while x:
if a == 2:
print(f'{a} is prime')
x = False
else:
x = True
if a %y == 0:
print(f' {a} is not prime')
x = False
else:
y = y + 1
if y >= b:
print(f'{a} is prime')
x = False
else:
x = True
Here is the Simple program for the output
def isPrime(lower,upper):
for num in range(lower,upper+1):
if num > 1:
for i in range(2,num):
if (num % 1) == 0:
break
else:
print(num," is a prime number")
def isDivisible(lower,upper):
for num in range(lower,upper+1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num," is divisible by ", i)
else:
pass
else:
pass
Lower = int(input("Enter your Lower limit"))
Upper = int(input("Enter Your Upper Limit"))
isPrime(Lower,Upper)
isDivisible(Lower,Upper)
**This is the output to code:**
2 is a prime number
4 is divisible by 2
6 is divisible by 2
6 is divisible by 3
8 is divisible by 2
8 is divisible by 4
9 is divisible by 3
10 is divisible by 2
10 is divisible by 5
isPrime() function will check whether the number is prime or not
isDivisible() function will check whether the number is divisible or not.
This piece of code receives a number from the user and determines whether it is prime or not. I can say that it is the fastest because in mathematics, to find out whether a number is prime or not, it is enough to examine the square root of that number.
import math
prime = int(input("Enter your number: "))
count = 0
sqr = int(math.sqrt(prime))
for i in range(2, sqr+1):
if prime % i == 0:
print("your number is not prime")
count += 1
break
if count == 0:
print("your number is prime")