Is number prime? (no recursion or loops) - python

I am given the following function:
def divides(n):
def div(k):
return n % k == 0
return div
I need to determine if the inputted number is prime, but I cannot use any recurssions or loops. Does anyone know how to go about this?
I was told to use sum, map, and the divides function above, but I'm not exactly sure how to do that.
EDIT:
I've tried this, but I'm not sure how to input the k in div:
def prime(n):
lst = range(1, n**.5)
result = map(divides(n), lst)
return result
EDIT2:
I am getting an answer, but they are all False. Any ideas?
def prime(n):
lst = range(1,1+int(n**.5))
result = map(divides(n), lst)
return sum(result) == 0

one liner version
def isPrime(n):
return 0 == sum(map(divides(n),range(2,1+int(n**.5))))

This is the final code that works for me:
def prime(n):
lst = range(1, 1+int(n**.5))
result = map(divides(n), lst)
return sum(result) == 1

Related

avoid for/else in this prime numbers generator function, use pure for loop

I am doing an exercise about generator to generate prime numbers.
Even though I've got a solution about this problem. I wonder if I don't know or want to use for/else loop. How can I make it with only for loop.
def genPrimes():
primes = [] # primes generated so far
last = 1 # last number tried
while True:
last += 1
for p in primes:
if last % p == 0:
break
else:
primes.append(last)
yield last
You can use recursive functions if you want to :
def prime_number(n, d):
if n//2 < d:
return True
if n%d == 0:
return False
return prime_number(n, d+1)
def find_primes(n,i, result):
if i == n + 1:
return result
if prime_number(i, 2):
result.append(i)
return find_primes(n, i+1, result)
print(find_primes(100,2, []))
Using loops is better here because its simpler and avoids stack overflow ;)

Python print non-prime numbers

I have a hackkerank coding challenge to print first n non prime numbers, i have the working code but the problem is that they have a locked code which prints numbers from 1 to n along with the output, in order to pass the test i need to print only the non prime numbers not 1...n numbers along with it. I cant comment the printing part of 1...n as it is blocked. please let me know the idea to print only 1st n non prime numbers:
here is my solution:
def manipulate_generator(generator, n):
if n>1:
ls=[1]
for elm in generator:
if elm>3 and len(ls)<n:
for k in range(2,elm):
if elm%k==0 and elm not in ls:
ls.append(elm)
print(elm)
if len(ls)==n:
return ls
That's the code I added but here is the code that's locked on which I have to write the code above to make it print the number one at a time
def positive_integers_generator():
n = 1
while True:
x = yield n
if x is not None:
n = x
else:
n += 1
k = int(input())
g = positive_integers_generator()
for _ in range(k):
n = next(g)
print(n)
manipulate_generator(g, n)
the point is the for _ in range(k): already prints out number which includes numbers I don't want printed out: This is the desired kind of output I want:for n=10 I want it to print out:
output:
1
4
6
8
9
10
12
14
15
16
I can't change this code but the one above is what I wrote and can be changed... Pleae help me out... Thanks in anticipation
Why not to throw away the numbers which we don't need? Look at this solution which I implemented...
def is_prime(n):
for i in range(2, n):
if n%i == 0:
return False
return True
def manipulate_generator(generator, n):
if is_prime(n+1):
next(generator)
manipulate_generator(generator, n+1)
Note: I understand that the logic can be improved to make it more efficient. But, its the idea of skipping unnecessary number printing which is important here !
You can print all the numbers from 1 up to the first prime number and then from that first number to the next one until you reach n.
I'm not sure of your hackerrank situation, but printing the first N non-prime numbers efficiently can be done this way.
def non_prime_numbers_till_n(n):
primes = set()
for num in range(2,number + 1):
if num > 1:
for i in range(2, math.sqrt(num)):
if (num % i) == 0:
break
else:
primes.add(num)
result = []
for i in range(1, n):
if i not in primes:
result.append(i)
return result
Depending on what your online editor expects you can either print them, or store them in a list and return the list.
Also bear in mind, you can only check upto the sqrt of the number to determine if its a prime or not.
I eventually came up with this answer which I believe should solve it but id there;s a better way to solve it please add your answers:
def manipulate_generator(generator, n):
for num in range(3,100000):
for q in range(2,num):
if num%q==0 and num>n:
generator.send(num-1)
return
this link python generator helped me to understand python generator
I just solved that right now. Like Swapnil Godse said you need to deal with all special cases to optimize computations. This link might be helpful: click here.
Here is the solution:
from math import sqrt
def is_prime(n):
if (n <= 1):
return False
if (n == 2):
return True
if (n % 2 == 0):
return False
i = 3
while i <= sqrt(n):
if n % i == 0:
return False
i = i + 2
return True
def manipulate_generator(g, n):
if is_prime(n+1):
next(g)
manipulate_generator(g, n+1)
prime = int(input('Please enter the range: '))
prime_number = []
for num in range(prime):
if num > 1:
for i in range(2,num):
if num % i == 0:
break
else:
prime_number.append(num)
print(f'Prime numbers in range {prime} is {prime_number}')
all_number = []
for i in range(2,prime+1):
all_number.append(i)
Non_prime_number = []
for element in all_number:
if element not in prime_number:
Non_prime_number.append(element)
print(f'Non Prime numbers in range {prime} is {Non_prime_number}')

Finding Divisors (Codewars Issue)

I'm doing a Codewars problem that states:
Create a function named divisors/Divisors that takes an integer n > 1
and returns an array with all of the integer's divisors(except for 1
and the number itself), from smallest to largest. If the number is
prime return the string '(integer) is prime'
I came up with the code:
def divisors(integer):
newlist = []
for x in range(2, integer):
if integer%x==0:
newlist.append(x)
if len(newlist) == 0:
return str(integer) + " is prime"
return newlist
I feel like this should work, and it does for most of the tests, but whenever the first divisor is odd, it doesn't work. For example, 15 and 9 don't work. I know this isn't the optimal way to do this, but I was just wondering why it works for some numbers and doesn't for others.
Your indentation was wrong:
def divisors(integer):
newlist = []
for x in range(2, integer):
if integer%x==0:
newlist.append(x)
if len(newlist) == 0: # this _was_ being executed after just the first iteration
return str(integer) + " is prime"
return newlist
works
And also one thing instead of len(newlist)==0 you can just do not newlist:
def divisors(integer):
newlist = []
for x in range(2, integer):
if integer%x==0:
newlist.append(x)
if not newlist:
return str(integer) + " is prime"
return newlist
print(divisors(15))
Your second if statement is within the for loop so it returns while evaluating x = 2.
Move it out of the for loop and it should work.
You may use
for x in range(2, (integer//2)+1):
instead of
for x in range(2, integer):
to cut the time required into half.
A divisor greater than integer/2 cannot yield the desired result.

python - finding circular prime number

I am trying trying to find the number of circular primes from a given limit. The prime(x) will return whether a number is a prime or not. The rotations() will return a list of rotated numbers. Lastly, prime_count() will output the total amount of circular primes based on the given limit. Both prime() and rotations() gave me the correct output; however, prime_count() is not incrementing like it should. Any ideas on what i did wrong?
def prime(number): #return true or false
return all(number% i for i in range(2,number))
def rotations(num): #rotating number and return list
list = []
m = str(num)
counter = 0
while counter < len(str(num)):
m=m[1:] + m[0]
list.append(int(m))
counter+=1
list1=sorted(list,key=int)
return list1
def prime_count(limit): #return numbers of circular primes from given limit
counter = 0
for i in range(1,limit+1):
a=rotations(i)
for j in a:
if j == prime(j):
counter+=1
return counter
print(prime_count(100))
There are a few problems with your code:
Your prime function has a bug:
In [8]: prime(1)
Out[8]: True
It erroneously returns True for any number less than 2 due to range(2, n) being empty and any([]) == True.
prime_count should be counting the total number of circular primes below limit. prime(j) returns a boolean, but you check j == prime(j), which can only be true if j is zero or one, which definitely isn't what you want. Try creating an is_circular_prime function that takes in an integer n and returns whether or not the prime is circular. Then, prime_count becomes easy to write.
This is the heart of the problem:
a=rotations(i)
for j in a:
if j == prime(j):
counter+=1
You're counting the wrong thing (e.g. 13 counts twice independent of 31 counting twice) and you're comparing the wrong thing (numbers against booleans.) The problem is simpler than you're making it. Rearranging your code:
def prime(number):
return number > 1 and all(number % i != 0 for i in range(2, number))
def rotations(num):
rotated = []
m = str(num)
for _ in m:
rotated.append(int(m))
m = m[1:] + m[0]
return rotated
def prime_count(limit):
counter = 0
for number in range(1, limit + 1):
if all(prime(rotation) for rotation in rotations(number)):
counter += 1
return counter
print(prime_count(100))
Note that you don't need to sort the rotations for this purpose. Also list, or any other Python built-in function, is a bad name for a variable.
Problem may be here:
for i in range(1,limit+1):
a=rotations(i)
for j in a:
if j == prime(j): # Prime will return True or False, comapring with J will cause it False ,except when J = 1
counter+=1
Changing it to prime(j)
for i in range(2,number//2):
if(number%i==0):
return False
return True
def rotations(num):
count=0
rotation_lst=[]
num=str(num)
while(count<len(num)):
num=num[1:]+num[0]
count+=1
rotation_lst.append(int(num))
rotation_lst1=sorted(rotation_lst,key=int)
return rotation_lst1
def get_circular_prime_count(limit):
count=0
for i in range(1,limit+1):
a=rotations(i)
for j in a:
if(check_prime(j)):
count+=1
return count
print(get_circular_prime_count(1000) ```

List of prime numbers - unexpected output

output: <generator object <genexpr> at 0x00000293AA2F8E60> instead of the list of prime numbers that I was attempting to obtain.
import math
#here i try to use trial division to validate whether a number is false or not
def isPrime(n):
d = {}
u = math.floor(math.sqrt(n))
i = 2
while (i <= u):
if (n % i == 0):
return False
i +=1
return True
#here I attempt to find all the prime numbers between 1 and 5000
print(isPrime(n) for n in range(1,5000))
You built a generator, and then told Python to print that object. That's what you got. From your description, I think that you want a list comprehension that will give you a list of primes.
Try this:
print ( [n for n in range(1, 5000) if isPrime(n) ] )
Note that you want to print the prime number, not the return value from isPrime.
I think what you're trying to do is this:
import math
def isPrime(n):
u = math.floor(math.sqrt(n))
i = 2
while (i <= u):
if (n % i == 0):
return False
i +=1
return True
for n in range(1, 5000):
print(isPrime(n))

Categories

Resources