for n in range(2, 6):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n // x)
break
elif x + 1 == n:
print(n, 'is a prime number')
Result:
3 is a prime number
4 equals 2 * 2
5 is a prime number
Can anybody explain me the double for loop, why does it skip the number 2? Is it because the last number is not included in for x in range (2,2), how does this program work when iterates using 3, I tried doing the second for loop by itself using 3 and i get 2 and on another line 3, so what does it do in the third line with n%x ==0. And what does it do in the 6th line using 3? Thank you I'd appreciate it if you can walk me through this.
for n in range(2, 6):
means for n in the numbers 2 up to, but not including 6.
So, start with n = 2
The next line says
for x in range(2, n):
n is currently 2, so this means no numbers (from 2 while less than 2).
It then uses the next value for n, namely 3.
This will use range(2,3) i.e. just the number 2.
And so on.
I suggest initially just seeing what the loops do, without any code to find prime numbers.
for n in range(2, 6):
print n
for x in range(2, n):
print x
The prime number logic breaks from the loop if it finds a divisor of n
Related
Q:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10001st prime number?
My code is:
def is_prime(num):
if all(num % i != 0 for i in range(2, num)):
return True
else:
return False
def find_nth_prime(nth):
lst_prime = []
num = 2
while len(lst_prime) < nth:
if is_prime(num):
lst_prime.append(num)
print(len(lst_prime), ":", lst_prime[-1])
num += 1
When I try to run find_nth_prime(6) it get stuck after finding "3" as prime. What am I missing here?
In your if statement inside while loop it keeps repeating at n=4 since n +=1 never happens as 4 is not a prime. Therefore take it out of the if statement.
Try using https://pythontutor.com/. It helps you visualize your code
def find_nth_prime(nth):
lst_prime = []
num = 2
while len(lst_prime) < nth:
if is_prime(num):
lst_prime.append(num)
print(len(lst_prime), ":", lst_prime[-1])
num += 1
Also you can do some improvments to your is_prime function. In that you don't have to take the whole range (2, num). It is enough to take the range 2 to square root of num. (2,int(num**0.5)+1) or use sqrt from python's math library
sum_ans=17
for i in range(11,2000000):
for j in range(2,int(i**0.5)):
if i%j==0:
break
else:
sum_ans+=i
print(sum_ans)
The code i have return gives answer 143064094781 and the correct answer is 142913828922 but i can not figure out where i have gone wrong. So can any one help me.
Range's stop parameter is exclusive. This means that your code is only calculating j from 2 to 1 less than i**0.5. To fix this you can add 1, meaning that your end code will look a little like this, providing the correct output of 142913828922:
sum_ans=17
for i in range(11,2000000):
for j in range(2,int(i**0.5+1)):
if i%j==0:
break
else:
sum_ans+=i
print(sum_ans)
What about about this:
def isPrime(x):
prime = True
for i in range(2, x):
if x % i == 0:
prime = False
break
else:
continue
return prime
primes = (a for a in range(2, 2000000) if isPrime(a))
print(sum(primes))
# output
142913828922
This code will take a few minutes to execute. Buckle up!!
def sumPrimes(n):
sum =0
for i in range(2 ,n):
for j in range(2, int(i / 2) +1):
if (i % j) == 0:
break
else:
sum += i
return sum
print(sumPrimes(2000000))
If you iterating over all numbers below 2 million, you might as well sieve them using the Sieve of Eratoshenes:
from math import ceil, sqrt
def sieve(n):
nums = list(range(2,n+1))
primes = []
p = 2
k = 1+ ceil(sqrt(n))
while p < k:
primes.append(p)
nums = [num for num in nums[1:] if num % p > 0]
p = nums[0]
return primes + nums
Then sum(sieve(2000000)) evaluates to 142913828922. It takes about 5 seconds to run on my machine.
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)
I have written a logic to find Prime Number up to some entered value. It is working fine but printing an unexpected 9 which don't go well with logic as 9%3 will be 0 and it have to skip that number.
n = int(input())
for i in range(2,n+1):
for j in range(2,n+1):
if i%j == 0 and i!=j:
break
else:
print(i,end=" ")
break
Input : 20
Output : 2 3 5 7 9 11 13 15 17 19
You output a candidate number as soon as it is found not divisible by any other number, so for the candidate number 9, as soon as the inner loop starts with the divisor number 2, it would immediately go into the else block and output the number and break the inner loop because 9 is not divisble by 2.
You should wait until all the divisors from the inner loop have exhausted before deciding that the candidate number from the outer loop is indeed a prime number, and for that you can use the for-else construct:
n = int(input())
for i in range(2, n + 1):
for j in range(2, n + 1):
if i % j == 0 and i != j:
break
else:
print(i, end=" ")
Sample input/output:
20
2 3 5 7 11 13 17 19
Just take a variable, e.g. is_prime to set it to True/False by checking if the number gets divided by any number in closed interval [2, n/2].
Do not decide immediately and come out of the loop once the if expression gets satisfied using break as you are doing.
With a tiny change in your code, you may make your code working and with less number of iterations (to decrease runtime complexity) as follows.
n = int(input())
for i in range(2,n+1):
is_prime = True
for j in range(2, n//2 + 1):
if i % j == 0 and i != j:
is_prime = False
break
if is_prime:
print(i, end= " ")
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]