I need to make this repeat with every number until 20,000 - python

My program is meant to check every number until 20,000 and spit out all of the palindromic prime numbers. I've made a checker, but for the love of me can't seem to find out how to extend it to 20,000
num = int(input("what's your number?: "))
temp=num
reverseNum = 0
while num > 0:
lastDigit = num % 10
reverseNum = reverseNum*10 + lastDigit
num = num//10
if temp == reverseNum:
print("the number is paliondromic")
else:
print("the number is not paliondromic")
if temp > 1:
for i in range(2, temp):
if (num % i) == 0:
print("{} is not a prime number".format(temp))
break
else:
print("{} is a prime number".format(temp))
Thanks in advance.

You can add a simple for loop, but I'll also make 2 suggestions:
Use Sieve of Eratosthenes to generate the primes, rather than a brute for check for each number.
Using string conversion for easier palindrome checking.
n = 20000
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n): #creating a Sieve using standard operations
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
for i in range(1, n+1): #palindrome checking
if prime[i] and str(i)==str(i)[::-1]:
print(i,"is a prime palindrome")
else:
print(i,"is not a prime palindrome")

Try this:
for temp in range(0,20000):
num = temp
reverseNum = 0
while num > 0:
lastDigit = num % 10
reverseNum = reverseNum*10 + lastDigit
num = num//10
if temp == reverseNum:
print("the number is paliondromic")
else:
print("the number is not paliondromic")
if temp > 1:
for i in range(2, temp):
if (num % i) == 0:
print("{} is not a prime number".format(temp))
break
else:
print("{} is a prime number".format(temp))

Related

I am trying to find the sum of all the prime numbers below a certain number. if the initial number is prime we return it

def sumPrimes(num):
sum = 0
if num>1:
for i in range(1, num):
if num % i == 0:
pass
else: sum = sum + i
return sum
print(sumPrimes(3))
i don't know why this isnt working pls help. I am trying to find the sum of all the prime numbers below a certain number. if the initial number is prime we return it.
Meaby It will help u
# Program to check if a number is prime or not
num = 407
# To take input from the user
#num = int(input("Enter a number: "))
# prime numbers are greater than 1
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 input number is less than
# or equal to 1, it is not prime
else:
print(num,"is not a prime number")
If you want to do this efficiently it's more complex than you might have imagined.
def genprime():
yield 2
D = {4:[2]}
q = 3
while True:
if q not in D:
yield q
D[q * q] = [q]
else:
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 2
def isprime(n):
if isinstance(n, int) and n >= 2:
g = genprime()
s = int(n ** 0.5)
while True:
d = next(g)
if d > s:
return True
if n % d == 0:
break
return False
def sumPrimes(n):
if isprime(n):
return n
g = genprime()
sum = 0
while (np := next(g)) < n:
sum += np
return sum
print(sumPrimes(12))
You'll need Python 3.7+ for this
This seems to work. If you want it to add 1 as a prime number change the second range to include 1.
def sumPrimes(num):
sum = 0
if num > 1:
if all(num % n for n in range(2, num)) == True: #check of prime
return num
else:
for i in range(2, num):
if all(i % n for n in range(2, i)) == True: #if you want it to add the number 1 as a prime number change this range to range(1,i)
sum += i
else:
continue
return sum
You can use is_prime to check if the number is prime in the loop:
import math
def is_prime(x):
for num in range(2, int(math.sqrt(x)) + 1):
if x % num == 0:
return False
return True
def sumPrimes(num):
return sum([x for x in range(2,num) if is_prime(x)])

Check given number is prime or not, if it is prime then find factorial of that number, if it is not prime then print sum-of-digit of that number

The sum of digit is running well, but Why is the factorial section not working? Is there any mistakes that I made with the if else, or the break ?
NUM = int (input ("Enter a number "))
if NUM > 1:
for x in range (2, NUM):
if (NUM % x) == 0:
temp = NUM
sod = 0
while temp > 0:
remainder = temp % 10
sod += remainder
temp = temp//10
print (sod)
break
else:
factorial = 1
for I in range (1, NUM + 1,1):
factorial *= I
print (factorial)
else:
temp = NUM
sod = 0
while temp > 0:
remainder = temp % 10
sod += remainder
temp = temp//10
print (sod)
Your break statement on line 12 is outside the if statement, so the for loop will break after the first pass regardless of the value of NUM. Are you sure you didn't mean to indent the break another four spaces?
# example of factorial with prime numbers
num = int(input("Enter a number"))
factorial = 1
if num%2 == 0:
for i in range(1, num + 1):
factorial = factorial*i
print("The factorial of ",num," is",factorial)
Below code checks if the number is prime or odd number. if its prime it finds the factorial of that number and if its odd number then it sums the range of the number. Hope its what you were looking for.
NUM = int(input("Enter number here"))
if NUM > 0:
if NUM % 2 == 0:
factorial = 1
for i in range(1, NUM +1):
factorial = factorial*i
print(factorial)
else:
sum_of_NUM = 0
for x in range(NUM+1):
sum_of_NUM += x
print(sum_of_NUM)
else:
print("something you want to put")

Prime number less than 501

I am trying to find all the prime numbers greater than 2 and less than 501. Please refer to my code given below:
num = 501
x = int(input('Enter a number greater than 1: '))
if x > 1:
for i in range(2, num):
if x % i == 0:
result = False
else:
result = True
if result == True:
print('Prime number.')
else:
print('Not a prime number.')
else:
print('Not a prime number.')
I tried to run the code for two numbers being 19 and 99. When I put a "break statement" after the code given below, I get the result of "99: not a prime number" but "19, being a prime is printed as not prime" and vice versa.
if x % i == 0:
result = False
break
Please correct the above code to print the correct output.
Instead of using trial division, it is much faster to use the Sieve of Eratosthenes, invented by a Greek mathematician over two thousand years ago:
def primes(n): # sieve of eratosthenes
i, p, ps, m = 0, 3, [2], n // 2
sieve = [True] * m
while p <= n:
if sieve[i]:
ps.append(p)
for j in range((p*p-3)/2, m, p):
sieve[j] = False
i, p = i+1, p+2
return ps
This function returns a list of primes less than n, sieving only on odd numbers and handling 2 separately. If you prefer to generate the primes rather than returning a list, use this:
def primegen(start=0): # stackoverflow.com/a/20660551
if start <= 2: yield 2 # prime (!) the pump
if start <= 3: yield 3 # prime (!) the pump
ps = primegen() # sieving primes
p = next(ps) and next(ps) # first sieving prime
q = p * p; D = {} # initialization
def add(m, s): # insert multiple/stride
while m in D: m += s # find unused multiple
D[m] = s # save multiple/stride
while q <= start: # initialize multiples
x = (start // p) * p # first multiple of p
if x < start: x += p # must be >= start
if x % 2 == 0: x += p # ... and must be odd
add(x, p+p) # insert in sieve
p = next(ps) # next sieving prime
q = p * p # ... and its square
c = max(start-2, 3) # first prime candidate
if c % 2 == 0: c += 1 # candidate must be odd
while True: # infinite list
c += 2 # next odd candidate
if c in D: # c is composite
s = D.pop(c) # fetch stride
add(c+s, s) # add next multiple
elif c < q: yield c # c is prime; yield it
else: # (c == q) # add p to sieve
add(c+p+p, p+p) # insert in sieve
p = next(ps) # next sieving prime
q = p * p # ... and its square
There is much more about primes at my blog.
If I'm not mistaken this will always return false for all numbers below 501 since when any inputed number will be divisible by itself.
You should also check if x != i.
This will work :
import math # This will import math module
def isprime(x):
if x > 1:
result = True
for i in range(2, int(math.sqrt(x))+1 ):
if ( x % i == 0):
result = False
break
if ( result == True):
print("Prime Number ")
else:
print("Not a Prime Number")
And do function call like:
isprime(19)
Please correct the above code to print the correct output.
I believe the following is both a simplified and corrected version of your code:
number = int(input('Enter a number greater than 1: '))
if number > 1:
for divisor in range(2, int(number ** 0.5) + 1):
if number % divisor == 0:
print('Not a prime number.')
break
else: # no break
print('Prime number.')
else:
print('Not a prime number.')
This code works but is not optimal. One simple optimization would be to handle 2/even as a special case and only divide by odd numbers starting at 3. A significant optimization would be to switch to a sieve approach as #user448810 suggests.
The code you provided only tests one number per user input. If you want to convert it to a loop that tests a range of numbers, say all numbers greater than 2 but less than 501, then we can do:
for number in range(3, 501):
if number > 1:
for divisor in range(2, int(number ** 0.5) + 1):
if number % divisor == 0:
print(number, 'is not a prime number.')
break
else: # no break
print(number, 'is a prime number.')
else:
print(number, '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)

Categories

Resources