Printing prime numbers in range - python-3.x

k=int(input())
res=[2]
for i in range(2,k+1):
if i%2==0:
continue
else:
for j in range(2,i):
if i%j==0 or j%2==0 :
break
else:
res.append(i)
print(res)
This code is for finding prime numbers in a given range of numbers.
I tried to run the code but the list is having only number 2. Can anyone tell me what is happening?
If I remove j%2==0 it's working. I just want to know my mistake.

You should use your current result to accelerate your process. You only need to test divisibility by primes. But you are building a list of primes. So use it !
k=int(input())
primes=[]
for i in range(2,k+1):
if all(i%p!=0 for p in primes):
primes.append(i)
You can also improve by selecting only prime elements which are inferior to sqrt(i) like others suggested.
import math
k=int(input())
primes=[]
for i in range(2,k+1):
j=math.sqrt(i)
if all(i%p!=0 for p in primes if p<=j):
primes.append(i)

Your code had one issue, in the inner loop the or condition is incorrect, as highlighted by #kederrac. You don't need the j%2==0 as j always start from 2 and i%j==0 already covers the condition
k=int(input())
res=[2]
for i in range(2,k+1):
if i%2==0:
continue
else:
for j in range(2,i):
if i%j==0 :
break
else:
res.append(i)
print(res)

in your inner loopj variable starts from value 2 and then you have an if statement that is always True because j%2==0 is always 2%2==0 which is always True, so you always break from the first step of inner for loop iteration
you can use:
import math
k=int(input())
res=[]
for i in range(2, k+1):
for x in range(2, int(math.sqrt(i) + 1)):
if i % x == 0 :
break
else:
res.append(i)
# k = 20
output:
[2, 3, 5, 7, 11, 13, 17, 19]
for efficient prime generation, you can use the Sieve of Eratosthenes:
# Sieve of Eratosthenes
# Code by David Eppstein, UC Irvine, 28 Feb 2002
# http://code.activestate.com/recipes/117119/
def _gen_primes():
""" Generate an infinite sequence of prime numbers.
"""
# 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
k=int(input())
def gen_primes(k):
gp = _gen_primes()
p = next(gp)
while p < k:
yield p
p = next(gp)
res = list(gen_primes(k))

Related

Twin Primes Python Program

I need to write a Python program that determines whether a given integer input is is a twin prime number or not. If the input number is a twin prime, the program must output true. Otherwise, it must output false.
Please may someone guide me with how this program should be written in Python?
This is what I have done so far. I am stuck at the is_twin_prime function part.
def is_prime(x):
for i in range(2, x):
if x % i == 0:
return False
return True
def is_twin_prime(x):
if is_prime(x) = True:
N = int(input())
for i in range(N):
p = int(input())
if is_twin_prime(p):
print("true")
else:
print("false")
Based on the assumption, that you are trying to determine if N & p are twin primes of one another, I found several issues with your code as follows:
the is_twin_prime function has no False return
the is_prime function always starts with 2 and iteratively checks for prime, this is very inefficient.
To provide an answer, I started with the following factoids about twin_primes:
both numbers must be prime
abs(n-p) == 2
n and p must each have a units digit in [0, 2, 3, 5, 7, 8]
To make the function testing for twin primes as efficient as possible, I eliminated any numbers not meeting the last two cases first, and only if necessary did I generate a list of primes. Also, when generating the primes, I only did it once for the largest number since, once I have the list or the largest both numbers must be in the list.
To make searching for primes more efficient I employed itertools, although this could be done with slightly less efficiency without it's use.
import itertools
def erat2():
D = { }
yield 2
for q in itertools.islice(itertools.count(3), 0, None, 2):
p = D.pop(q, None)
if p is None:
D[q*q] = q
yield q
else:
x = p + q
while x in D or not (x&1):
x += p
D[x] = p
def generatePrimes(given_number):
"""
Returns the prime number <= given_number using
an adaptive sieve of estraothenes approach
"""
return list(itertools.islice(erat2(), given_number))
def is_twinPrime(n, p):
accepted_digits = [0, 2, 3, 5, 7, 8]
if abs(n-p) != 2:
return False
elif n%10 not in accepted_digits and p%10 not in accepted_digits:
return False
else:
primes = generatePrimes(max(n, p))
if n in primes and p in primes:
return True
return False
N = int(input("Enter first number"))
P = int(input(Enter second number"))
print(istwinPrime(N, P)

Printing first combination among various combinations

So I have a question:
Given an even number (greater than 2), return two prime numbers whose sum will be equal to given number. There are several combinations possible. Print only first such pair
This is for additional reference:
*Input: The first line contains T, the number of test cases. The following T lines consist of a number each, for which we'll find two prime numbers.
Note: The number would always be an even number.
Output: For every test case print two prime numbers space separated, such that the smaller number appears first. Answer for each test case must be in a new line.
Constraints: 1 ≤ T ≤ 70
2 < N ≤ 10000
Example:
Input:
5, 74, 1024, 66, 8, 9990
Output: 3 71, 3 1021, 5 61, 3 5, 17 9973
Here is what I tried:
import math
def prime(n):
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
T = int(input("No of inputs: ")) #T is the no of test cases
input_num = []
for i in range(0,T):
input_num.append(input())
lst2= []
if T in range(1,71):
for i in input_num:
if (i in range(3,1000)) and (i % 2 == 0):
for j in range(0,i):
if prime(j) == True:
lst2.append(j)
for x in lst2:
for y in lst2:
if x + y == j:
print(x,end = ' ')
print(y)
This is only taking inputs but not returning outputs.
Also my code is currently intended for all the combinations but what I want is only the first pair and I am not able to do that
I found a more elegant solution to this problem here. Java, C, C++ etc versions of solution is also present there. I am going to give the python3 solution.
# Python 3 program to find a prime number
# pair whose sum is equal to given number
# Python 3 program to print super primes
# less than or equal to n.
# Generate all prime numbers less than n.
def SieveOfEratosthenes(n, isPrime):
# Initialize all entries of boolean
# array as True. A value in isPrime[i]
# will finally be False if i is Not a
# prime, else True bool isPrime[n+1]
isPrime[0] = isPrime[1] = False
for i in range(2, n+1):
isPrime[i] = True
p = 2
while(p*p <= n):
# If isPrime[p] is not changed,
# then it is a prime
if (isPrime[p] == True):
# Update all multiples of p
i = p*p
while(i <= n):
isPrime[i] = False
i += p
p += 1
# Prints a prime pair with given sum
def findPrimePair(n):
# Generating primes using Sieve
isPrime = [0] * (n+1)
SieveOfEratosthenes(n, isPrime)
# Traversing all numbers to find
# first pair
for i in range(0, n):
if (isPrime[i] and isPrime[n - i]):
print(i,(n - i))
return
# Driven program
n = 74
findPrimePair(n)

Dynamic Programming Primitive calculator code optimization

I am currently doing coursera course on algorithms. I have successfully completed this assignment. All test cases passed. My code looks messy and I want to know if there is any thing availiable in Python which can help run my code faster. Thanks
The problem statement is as follows: You are given a primitive calculator that can perform the following three operations with
the current number 𝑥: multiply 𝑥 by 2, multiply 𝑥 by 3, or add 1 to 𝑥. Your goal is given a
positive integer 𝑛, find the minimum number of operations needed to obtain the number 𝑛
starting from the number 1.
# Uses python3
import sys
def optimal_sequence(m):
a=[0,0]
for i in range(2,m+1):
if i%3==0 and i%2==0:
a.append(min(a[i//2],a[i//3],a[i-1])+1)
elif i%3==0:
a.append(min(a[i//3],a[i-1])+1)
elif i%2==0:
a.append(min(a[i//2],a[i-1])+1)
else:
a.append((a[i-1])+1)
return backtrack(a,m)
def backtrack(a,m):
result=[]
result.append(m)
current = m
for i in range(a[-1],0,-1):
if current%3==0 and a[current//3]==(i-1):
current=current//3
result.append(current)
elif current%2==0 and a[current//2]==(i-1):
current = current//2
result.append(current)
elif a[current-1]==(i-1):
current = current-1
result.append(current)
return result
n = int(input())
if n == 1:
print(0)
print(1)
sys.exit(0)
a= (optimal_sequence(n))
print(len(a)-1)
for x in reversed(a):
print(x,end=" ")
I would use a breadth first search for number 1 starting from number n. Keep track of the numbers that were visited, so that the search backtracks on already visited numbers. For visited numbers remember which is the number you "came from" to reach it, i.e. the next number in the shortest path to n.
In my tests this code runs faster than yours:
from collections import deque
def findOperations(n):
# Perform a BFS
successor = {} # map number to next number in shortest path
queue = deque() # queue with number pairs (curr, next)
queue.append((n,None)) # start at n
while True:
curr, succ = queue.popleft()
if not curr in successor:
successor[curr] = succ
if curr == 1:
break
if curr%3 == 0: queue.append((curr//3, curr))
if curr%2 == 0: queue.append((curr//2, curr))
queue.append((curr-1, curr))
# Create list from successor chain
result = []
i = 1
while i:
result.append(i)
i = successor[i]
return result
Call this function with argument n:
findOperations(n)
It returns a list.

How to print prime numbers in the 'list'

I have obtained input from user and put its factors to a new list.How do i check for prime numbers in the list.
a=int(input())
b=[]
for x in range(2,a):
if(a%x)==0:
b.append(x)
print(b)
Here you can print the list of factors and then iterate through the list of factors and this program will print out the ones that are prime. Instead of printing it you could also append it to another list by replace the print(n) with something else.
import math
a=int(input())
b=[]
for x in range(2,a):
if(a%x)==0:
b.append(x)
print(b)
def is_prime(n): #calling a function
if n == 2:
print(n) #if one of the factors is 2 it prints it because it is a prime number
if n % 2 == 0 or n <= 1: # if it is less than one or is a factor of 2 it returns false and does nothing
return False
sqr = int(math.sqrt(n)) + 1
for divisor in range(3, sqr, 2): #checks for other divisors
if n % divisor == 0:
return False
print(n) #otherwise it prints out the number since it is a prime number
for n in b: #iterates through the list of factors and checks if they are prime
is_prime(n)
If we run this and I input 10 it returns this :
[2, 5]
2
5
EDIT :
When you input a prime number it returns a blank array. So i edited the code to be :
import math
values = []
def is_prime(n): #calling a function
if n == 2:
values.append(n)
#print(n) #if one of the factors is 2 it prints it because it is a prime number
return True
if n % 2 == 0 or n <= 1: # if it is less than one or is a factor of 2 it returns false and does nothing
return False
sqr = int(math.sqrt(n)) + 1
for divisor in range(3, sqr, 2): #checks for other divisors
if n % divisor == 0:
return False
#print(n) #otherwise it prints out the number since it is a prime number
values.append(n)
return True
a=int(input())
b=[]
for x in range(2,a):
if(a%x)==0:
b.append(x)
if is_prime(a)==True: #if the inputted number is prime it automatically appends that number to the list and breaks since prime numbers don't have any other factors
b.append(a)
break;
print(b)
for n in b: #iterates through the list of factors and checks if they are prime
is_prime(n)
def remove_duplicates(values): #here it checks for duplicates
output = []
seen = set()
for value in values:
# If value has not been encountered yet,
# ... add it to both list and set.
if value not in seen:
output.append(value)
seen.add(value)
return output
# Remove duplicates from this list.
values = remove_duplicates(values)
print("Here are the prime factors :")
print(values) #prints out the values
Now if you input a prime number it returns :
[7]
Here are the prime factors :
[7]
And any other number such as 20 :
[2, 4, 5, 10]
Here are the prime factors :
[2, 5]
will still run.
Note : I changed it from printing out just the numbers to appending the numbers to an array and then printing out the array.
Here is a one liner, you can change lower and upper limit by changing 1 and 150. Assign this to a variable. Not as fast as SoA though
[i for i in range(1,150) if all(i%j for j in range(2,int(i**(1/2))+1)) and i != 1]

Having trouble printing the final list when appending to a list

def eratos(n):
numbers = []
prime = [True for i in range(n+1)]
p=2
while(p <= n):
if (prime[p] == True):
for i in range(p * 2, n+1, p):
prime[i] = False
p+=1
lis =[]
# Print all prime numbers
for p in range(2, n):
if prime[p]:
numbers.append(p)
print(numbers)
if __name__:
n = 12
eratos(n)
This will print
whereas I'd only like the last list [2,3,5,7,11].
I understand the for loop I have will check if there is a prime number in my set range then add it into my list then repeat and check for the next number. If possible I'd like for it to check all numbers in the range and then append all of them at the same time, or append one at a time but only return the final list.
That's because the print statement is in the for loop. Simply move it outside:
for p in range(2, n):
if prime[p]:
numbers.append(p)
print(numbers) # outside for loop
Now the numbers list will be printed after the for loop is done. A final remark: why do you construct lis? You never seem to use it.
You can also improve the readability (and a bit of efficiency) with:
def eratos(n):
prime = [True] * (n+1)
for p in range(2,n+1):
if prime[p]:
for i in range(2*p,n+1,p):
prime[i] = False
# Print all prime numbers
numbers = [p for for p in range(2,n) if prime[p]]
print(numbers)

Resources