Return prime numbers - python

The function should return a list of prime numbers between m and n. If m and/or n are prime numbers, they should also be included in the list.
Here's what I have done:
Code
Here's the output that is supposed to be:
Please ignore the first two output as I have done them.
Output file

import sys
sys.setrecursionlimit (30000)
"""The checkprime function uses the prime factor theorum to determine if a number is prime by checking it against a list of
prime numbers and ensuring it is not divisible by said numbers, therefore ensuring it is a prime, it requires a list of all prime numbers
smaller than the number being checked itself"""
def checkprime(primelist,value,recursions):
#Decrease the index that is being looked at
recursions -= 1
#If the prime is not on
if recursions == -1:
return(True)
if value%primelist[recursions] == 0:
return(False)
return(checkprime(primelist,value,recursions))
'''The compileprimes function returns a list of all the prime numbers below the maximum value, using a list of primes,the function starts with a list of the first few prime numbers as a
default value and works up from there, its start value is naturally set to the following prime to avoid unneccesary checks'''
def compileprimes(Up_To,primelist=[2,3,5,7],start=11):
#Base case: If the value to compare is greater than the maximum value return the list of primes
if start > Up_To:
return(primelist)
#Use the checkprime function to check if the 'start' value is a prime
if checkprime(primelist,start,len(primelist)):
#If the 'start' value is prime, append it to the list of primes
primelist.append(start)
#Increase by two to skip all even numbers
start += 2
#Recursive step
return(compileprimes(Up_To,primelist,start))
The compileprimes function will recursively create a list of prime numbers up until and below the number you enter.
eg.
'''
>>> compileprimes(23)
[2,3,5,7,11,13,17,23]
'''
An issue you may encounter is that the primelist array may have to be assigned to the default upon calling the function again, however this method is considered to be much more efficient than the solution presented before as it does not divide by any non-prime numbers (which themselves are products of prime numbers), it also should work much faster than the previous example.
It is easy enough to remove any numbers under the n-value, so I'll leave that to you

def primes(m, n):
list_of_primes = [] # Keep track of primes
for num in range(m, n + 1): # make inclusive of upper bound
is_prime = True # Assume number is prime as starting condition
for i in range(2, num): # Check remainder from number 2 up to num
if num % i == 0:
is_prime = False
break
if is_prime and num > 1: #EDIT HERE
list_of_primes.append(num) #add to the list of primes if True
return list_of_primes
Note there are multiple ways to improve this algorithm, such as not checking even numbers ect, but this fits the criteria defined in your question.

Related

I want a list of all the prime numbers that are smaller than a integer

Hey so i have these two functions. The first one checks whether a number is a prime number which works. The second one is supposed to take a number and have all the prime numbers that are smaller than that number added into a sorted list. This is the code i have right now,
def is_prime(n):
flag = True
if n == 1:
flag = False
for i in range(2, n):
if (n % i) == 0:
flag = False
return flag
def primes(num):
primelist = []
flag = is_prime(num)
for i in range(1, num - 1):
if flag == True:
primelist.append(num)
return sorted(primelist)
How would i go about adding all the prime numbers lower than a integer into the list?
You've almost got it!
The issue in your primes function is that flag is computed outside of the loop. So it's computed only once for the input num.
Instead, it should be computed for every loop entry.

pythion Check number is prime

HELP :
A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. For Example, 5 prime .8 is not prime because it has list of [1,2,4,8]as its divisors. Implement The function isPrime() which determines if a number is prime or not.
- The parameter of this function are num(int) and(list).We Assume that number is an integer greater than 1 and L is an empty list.This Assumption Does Not Need To Be Checked.
-The function returns True if num is prime and return False otherwise
-If Num Is Not Prime, the list of divisors of numis assigned L and printed. The list includes 1 and num. When number is prime , L can be any value and is not printed.
def isPrime(num, L):
# Implement the function here
# If syntax error occurs, no point will be given for this function
# Do not change the function header
ans = isPrime(8,[]) # This cell is for your confirmation, can be removed.
print(ans) # If correctly implemented, [1,2,4,8] is printed first, and False is printed at the
This seems like a homework question. Anyhow; run
for i in range(1, num/2):
if num % i == 0:
L.append(i)
to get the list of divisors.
Then; if the length of the list (len(L)) is more than 2, return false and print the list, else return true.

Check if a number is a prime by counting zero remainders

I am trying to write a program which checks if a number is a prime number or not.
The way I already know: Check if any of the numbers, excluding the number itself and 1, gives a reminder of zero.
The way I want to try: Check if more than two numbers, including 1 and the number itself, are giving a reminder of zero:
n=10
for a in range(1,n+1):
x=n%a
if (x == 0):
print x
I am getting the number of instances when the reminder is zero with code mentioned. I want to define the logic in such a way that if number of zeros is greater than 2 in the output, then the number is not prime, else the number is prime. (Expecting that the input number is greater than 1.)
I think folks are confused and avoiding this as it's not an efficient way to check for primes. Usually, we desire to disqualify a number as quickly and easily as possible, avoiding doing any extra divisions.
However, if it's what you want, here's an implementation:
def is_prime(n):
'''
I want to define the logic in such that if the number
of zeros is greater than 2 in the output, then the number
is not prime, else the number is prime
'''
return sum(n % divisor == 0 for divisor in range(1, n + 1)) <= 2
# Expecting that the input number is greater than 1
for n in range(2, 100):
if is_prime(n):
print(n)

Python Script Not Finishing

I am trying to run my code to try to solve euler problem number 10. I am very new to python and my code has been going very slowly and in this case never ending. Any help would be appreciated. Thank you.
primes = [2]
number = 2
y=1
while y <=1:
for i in primes:
if number % i == 0:
break
else:
if i == primes[-1]:
primes.append(number)
if (primes[-1]) >= 2000000:
del primes[-1]
y += 2
number+=1
print(sum(primes))
SPOILER ALERT: the following contains the answer to question 10 in Project Euler.
Your problem is that your code take too long to run, that is because it is checking too many thing and will take too long to work. In PE question you usually have to think of a trick to get your program to get the result fast enough. In this case you need to understand why there is no need to check weather a prime is divisible by a prime that is bigger the the square root of the number.
If a number x was divisible by a prime number p that is bigger than the square root of x, that would mean that there is a natural number n that is n = x/p, if p is bigger than the square root of x then n is smaller than the square root of x (think about why this is true). That means that we would find that the number x is also divisible by the number n that is smaller than the square root of x. That means we would have already found that x is divisible by n (or a prime factor of n) when we were checking all the numbers that are smaller than the square root of x, therefor there is no need to check any number bigger then the square root of a number is order to know if it is prime Q.E.D .
This way you can save A LOT of computations. the following is a python program that implements this idea:
import math
primes = [2]
is_prime = True
# loop over all the ODD numbers from 3 to 2,000,000 (no need to check even numbers)
for number in xrange(3, 2000000 + 1, 2):
sqrt = math.sqrt(number)
# loop over all the primes we have so far
for prime in primes:
# if the number we are checking is divisible by a prime it is not prime and we can move on to the next number
if number % prime == 0:
# we set this value to false so that when we finish the loop we will be able to know if the number is prime or not
is_prime = False
break
# this line is where the clever part is, if we already checked `all the primes that are smaller than square root of x, and we did not find any primes that our number is divisible by, then we will not find any primes higher than the square root of the number that the number is divisible by`
if prime > sqrt:
break
if is_prime:
primes.append(number)
else:
is_prime = True
# we are done, print the answer
print sum(primes)
As much as I appreciate the detailed answer by #DonatPants, I believe that solution is too complicated. First, we don't need to calculate sqrt() when the simpler square will do (I.e. square both sides of the equation.) Second the order of tests seems backward, why check prime > sqrt after if number % prime == 0? If prime > sqrt, you don't need the other test. And what's with that boolean? My simpler approach to this problem:
primes = [2]
for number in range(3, 2000000 + 1, 2): # only test odd numbers
for prime in primes:
if prime * prime > number: # we're past sqrt, a prime!
primes.append(number)
break
if number % prime == 0: # a composite
break
print(sum(primes))
Redundantly computing prime * prime is an inefficiency. It doesn't make any difference for this range of numbers but if needed, you can keep a separate array of squares, enumerate the primes and use the index generated to access the square, which you save when you save the prime. Squaring just the primes is cheaper than square rooting all the numbers:
primes = [2]
squares = [4]
for number in range(3, 2000000 + 1, 2):
for index, prime in enumerate(primes):
if squares[index] > number:
primes.append(number)
squares.append(number * number)
break
if number % prime == 0:
break
print(sum(primes))
We're wasting space to avoid wasting time. But again, for this range of numbers, it's not worth it.

Determining whether a number is prime or not

I know it's been discussed many times; I've read it, but somehow I can't get it.
I want to write a program that determines if the entered number is prime or not.
One of the implementations I found somewhere on the Internet:
from math import *
def main():
n = abs(input("Enter a number: "))
i = 2
msg = 'is a prime number.'
while i <= sqrt(n):
if n % i == 0:
msg = 'is not a prime number.'
i = i + 1
print n, msg
main()
A couple of questions here:
In the above, what is i, and why does it have a starting value of 2?
What does i = i + 1 do in this program?
How does the interpreter know when to print 'is a prime number.' even though it is out of the body loop?
A prime number is a number that's only divisible by 1 and itself. The method it's using is to try dividing your candidate number n by every other number from 2 up to itself; however if any number i is a divisor of your number n then so is n / i and at least one of them is less than or equal to sqrt(n) therefore we need only test up to sqrt(n) inclusive. In practice we need only test the divisors that are actually prime themselves but since we don't have a list of primes to hand we'll test every one.
what in the above i is? and why it got a 2 starting value?
i is the potential factor of n we're testing. It starts with 2 because we don't care if 1 divides n (and trivially it will) because the prime definition allows / expects that.
what is the i = i + 1 statement, in this concrete example for? Can't see its use in the program.
It's incrementing the i value at the end of the loop defined by the while i <= sqrt(n); it means we advance i to test the next candidate divisor of n.
and finally, how python knows when to print 'is a prime number.' although it is out of the body loop?
We initialise msg to "is a prime number" and if we find any divisor then we change it to "is not a prime number" inside the loop. If the loop doesn't find a divisor, or if the loop never runs, we'll use the initial value we set which is "is a prime number". Incidentally you could break out of the loop when you find a divisor; there's no point carrying on the test after that.
As another aside you probably want to compute sqrt(n) outside the while and store than in a variable to use in the while - you may be recalculating the square root for every iteration, which is relatively expensive.
I've added comments on the sides to explain what each line does:
from math import * # imports everything from the math module
def main():
n = abs(input("Enter a number: ")) # gets input from the user
i = 2 # starts off at 2 because all input is divisble by 1
msg = 'is a prime number.' # the message is initially set
while i <= sqrt(n):
if n % i == 0: # if 'i' divides evenly into n
msg = 'is not a prime number.' # only set if it isn't a prime
i = i + 1 # increases 'i' by 1 so it can check every value up to the square-root of 'n' (to see if it divides evenly)
print n, msg
main()
The program has to go through every value of i (up to the square-root of n) so that every possible factor is checked.
This is sort of a rough-prime checker, and inefficient for large numbers that aren't prime:
If the input was a number like 1234567890, it will iterate through every number up to the square root of that number, which is 35147 (rounded up).
Using return statements break the loop, so the first number you check, 2, it is declared not prime since it is evenly divisible by 2.
By using return, it will stop the function, and save you 35,146 calculations. That isn't a massive number (for computers, at least) but it's still more memory-efficient and takes less time.
def isPrime(n):
'''Checks if 'n' is prime.'''
from math import sqrt
if n == 0 or n == 1:
return False
else:
for check in range(2, int(sqrt(n))+1):
if n % check == 0: return False
return True

Categories