pythion Check number is prime - python

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.

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.

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: function which finds a prime, but also determines if the parameters entered is the sum of 2 primes

Would appreciate some feedback on a challenge I was recently given. In an interview the challenge was to write a function which takes only one number f(n) and returns a True if the number entered meets these conditions:
A prime number (which is easy enough to check)
the sum of 2 prime numbers
Without being able to enter a second number, there'd be a lot of recursions in the algorithm. Any pointers?
An example of a True would be f(5) where 5 is a prime number and the sum of 2 and 3 (which are also prime). But 1 + 4 is also 5, which is false.
Check to see if the number is prime (which you claim is easy enough), then check to see if two less than that number is prime.
There is only one even prime number (2). Since the the sum of two odd numbers is always even, the sum of any other two prime numbers (other than 2) will always be even, and therefore not prime. This means if a number, n, is prime, and is also the sum of two primes, then n-2 must be prime.
You can get the hint and help from this code which is using itertool approach :
import itertools
user_input=int(input())
def primecheck(int_1): #prime no check function
check_list = []
for item in range(1,int_1):
if int_1%item==0:
check_list.append(item)
if len(check_list)==1:
return 0
else:
return 1
if primecheck(user_input)==0: #if prime no is sum of two other prime no check function
def checker(int_2):
all = []
for item in range(2, user_input):
all.append(item)
only_prime = []
for item_1 in all:
if primecheck(item_1) == 0:
only_prime.append(item_1)
for check in itertools.product(only_prime, repeat=2):
sum_of_two_prime = check[0] + check[1]
if sum_of_two_prime == user_input:
return "{} is prime number and it is sum of {} and {}".format(user_input,check[0],check[1])
return "it is prime but not sum of any two other prime numbers"
print(checker(user_input))
else:
print("Its not prime , Please Enter a prime number")
Test_case1:
17
it is prime but not sum of any two other prime numbers
5
5 is prime number and it is sum of 2 and 3
13
13 is prime number and it is sum of 2 and 11

Return prime numbers

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.

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