I am trying to verify which numbers in the list are primes.
vetor = [2,3,4,5,11,15,20]
divisions_list = []
def isprime():
divisions = 0
i = 0
for i in range(1, vetor[i+1]):
if i % i == 0:
divisions = divisions + 1
divisions_list.append(divisions)
if divisions == 2:
print('The number {} is prime'.format(vetor[i]))
else:
print('The number {} is not prime'.format(vetor[i]))
print(isprime())
But this doesn't work, I'm only receiving:
The number 3 is not prime The number 4 is prime None
How can I fix this?
You already had a piece of code that takes a number and checks if it is a prime or not, then instead of using it you reinvented the wheel and broke it in the process (for example, you re-used i which caused a division by zero and tried to check if a list is equal to 2 instead of checking if its length is 2).
Use a function to reuse the working code with some improvements:
You don't really care how many numbers divide the number you check. It is enough that one number divides it in order for that number to not be prime
We can start the division check from 2, and it is proven mathematically that it is enough to go up to the square root of the number
from math import sqrt
def is_prime(n):
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
return False
return True
Then use it with the list of numbers:
vector= [2, 3, 4, 5, 11, 15, 20]
for n in vector:
if is_prime(n):
print(n, 'is a prime')
else:
print(n, 'is not a prime')
Outputs
2 is a prime
3 is a prime
4 is not a prime
5 is a prime
11 is a prime
15 is not a prime
20 is not a prime
max divisor of an integer x, is sure x//2 and not sqr(x) and not sqrt(x)+1 , this is mathematics
For example x=16, sqrt(x)=4, sqr(x)+1=5
But max divisor of 16 is 8 (really 16//2)
"""
verify prime or not in a list of number
"""
# my function :)
def isPrime(x):
"""
function get an integer as argument, and return True if this argument is prime and False if not
"""
i = 2
while i<=x//2 :
if x%i != 0:
i += 1
else:
return False
return True
# your code :)
vetor = [2,3,4,5,11,15,20]
# for all elements e in vetor
for e in vetor:
# test the return of isPrime function applied to arg e
if isPrime(e):
print("{} is prime number".format(e))
else:
print("{} is not prime number".format(e))
I believe the problem is simpler than you're trying to make it. You have most of the pieces you need but we need to add a couple of things, toss a bunch of stuff, and rearrange a bit:
vetor = [2, 3, 4, 5, 11, 15, 20]
def isprime():
for number in vetor:
if number < 2:
print('The number {} is not prime'.format(number))
continue
i = 2
while i * i <= number:
if number % i == 0:
print('The number {} is not prime'.format(number))
break
i += 1
else: # no break
print('The number {} is prime'.format(number))
isprime()
Much of the additional code that other answers include is about efficiency and there's lots to be learned. But the above is sufficient for the code to work.
OUTPUT
> python3 test.py
The number 2 is prime
The number 3 is prime
The number 4 is not prime
The number 5 is prime
The number 11 is prime
The number 15 is not prime
The number 20 is not prime
>
My favorite number to include in a prime test is 25 as using < instead of <= tends to turn it into a prime!
Related
I am trying to solve Project Euler number 7.
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 10 001st prime number?
First thing that came into my mind was using length of list. This was very ineffective solution as it took over a minute. This is the used code.
def ch7():
primes = []
x = 2
while len(primes) != 10001:
for i in range(2, x):
if x % i == 0:
break
else:
primes.append(x)
x += 1
print(primes[-1])
ch7()
# Output is: 104743.
This works well but I wanted to reach faster solution. Therefore I did a bit of research and found out that in order to know if a number is a prime, we need to test whether it is divisible by any number up to its square root e.g. in order to know if 100 is a prime we dont need to divide it by every number up to 100, but only up to 10.
When I implemented this finding weird thing happened. The algorithm included some non primes. To be exact 66 of them. This is the adjusted code:
import math
primes = []
def ch7():
x = 2
while len(primes) != 10001:
for i in range(2, math.ceil(math.sqrt(x))):
if x % i == 0:
break
else:
primes.append(x)
x += 1
print(primes[-1])
ch7()
# Output is 104009
This solution takes under a second but it includes some non primes. I used math.ceil() in order to get int instead of float but I figured it should not be a problem since it still tests by every int up to square root of x.
Thank you for any suggestions.
Your solution generates a list of primes, but doens't use that list for anything but extracting the last element. We can toss that list, and cut the time of the code in half by treating 2 as a special case, and only testing odd numbers:
def ch7(limit=10001): # assume limit is >= 1
prime = 2
number = 3
count = 1
while count < limit:
for divisor in range(3, int(number ** 0.5) + 1, 2):
if number % divisor == 0:
break
else: # no break
prime = number
count += 1
number += 2
return prime
print(ch7())
But if you're going to collect a list of primes, you can use that list to get even more speed out of the program (about 10% for the test limits in use) by using those primes as divisors instead of odd numbers:
def ch7(limit=10001): # assume limit is >= 1
primes = [2]
number = 3
while len(primes) < limit:
for prime in primes:
if prime * prime > number: # look no further
primes.append(number)
break
if number % prime == 0: # composite
break
else: # may never be needed but prime gaps can be arbitrarily large
primes.append(number)
number += 2
return primes[-1]
print(ch7())
BTW, your second solution, even with the + 1 fix you mention in the comments, comes up with one prime beyond the correct answer. This is due to the way your code (mis)handles the prime 2.
I'm new to Python and i'm working on a program which finds the prime factors of a number. My code so far looks like this:
num = int(input('\nEnter a natural number greater than 1: '))
if num <= 1:
while num <= 1:
num = int(input('\nI said greater than 1: '))
if num == 2:
print('\n', num, 'is a prime number.')
else:
toggle = 0
flist = []
for i in range(2, num - 1):
if num % i == 0:
flist.append(i)
toggle = 1
if toggle == 0:
print('\n', num, 'is a prime number.')
if toggle == 1:
print('\n', num, 'is not a prime number.')
print('\nIt\'s prime factors are:', flist)
With an input of 30 for example i get this output:
Enter a natural number greater than 1: 30
30 is not a prime number.
It's prime factors are: [2, 3, 5, 6, 10, 15]
The prime factors in this case are 2, 3, 5. How can i remove their multiples ?
Thank you.
I would define an extra function to check if a number is prime
def is_prime(n):
if n>1:
for i in range(2,n):
if (n % i)==0:
return False
return True
Then I would use it inside you code to check if a number is prime before to add it to the final list of prime factors.
num = int(input('\nEnter a natural number greater than 1: '))
if num <= 1:
while num <= 1:
num = int(input('\nI said greater than 1: '))
if num == 2:
print('\n', num, 'is a prime number.')
else:
toggle = 0
flist = []
for i in range(2, num - 1):
if num % i == 0:
if is_prime(i): # append only prime numbers
flist.append(i)
toggle = 1
if toggle == 0:
print('\n', num, 'is a prime number.')
if toggle == 1:
print('\n', num, 'is not a prime number.')
print('\nIt\'s prime factors are:', flist)
This gives you the right output:
Enter a natural number greater than 1: 30
30 is not a prime number.
It's prime factors are: [2, 3, 5]
You are getting the multiples of your prime factors, such as 6 = 2 × 3, 10 = 2 × 5 and 15 = 3 × 5.
To avoid those, you should divide your initial number by the prime factors as you find them, so that it won't divide again by the multiples of those prime factors.
Also, you should do that repeatedly, since numbers often have an exponent of a prime factor (for instance, 12 = 2² × 3, so you should divide by 2 twice.)
for i in range(2, num):
while num % i == 0:
flist.append(i)
num = num // i
if num == 1:
break
When you get to 1, you know you can stop.
There are also other optimizations you can do, for instance when i² is larger than num, you know num must be a prime, since you already divided it by all factors smaller than i.
You can also skip even numbers after 2, since those will never be factors.
Using the simple code above, you'll know that num is a prime whenever flist is empty. (You don't need an extra toggle to track that.) That works, since you're never dividing by num itself, so if you get to the end and haven't divided once, that means it's a prime.
For a number such as 12, your flist will have [2, 2, 3]. If you want the unique prime factors, without repetitions, you can use set(flist) to get rid of the duplicates.
Here's a solution using the Sieve of Eratosthenes to first find all primes beneath N and then go through those to find all prime factors, this should be pretty efficient
import numpy as np
def findSieve(num):
allN = np.arange(1,num+1,1)
mask = allN == allN
maskN = np.ma.MaskedArray(allN)
p = 2
while maskN[p:].count() > 0:
mask = mask & ((allN%p != 0) | (allN <= p))
maskN = np.ma.MaskedArray(maskN, mask =~ mask)
p = maskN[p:].min()
return np.asarray(maskN[maskN.mask == False])
def findPrimeFactors(num):
sieve = findSieve(num)
flist = []
num_factored = num
for i in range(1,len(sieve)) :
while num_factored % sieve[i] == 0:
flist.append(sieve[i])
num_factored = num_factored // sieve[i]
if num_factored == 1:
break
prime = len(flist) == 1
if prime:
print('\n', num, 'is a prime number.')
else:
print('\n', num, 'is not a prime number.')
print('\nIt\'s prime factors are:', flist)
num = int(input('\nEnter a natural number greater than 1: '))
findPrimeFactors(num)
for x in range (3,21):
if(x%2==0):
print (x,'is a not a prime number')
else:
print (x,'is a prime number')
This is my code but when it prints it says 9 is a prime number and 15 is a prime number.
Which is wrong because they aren't so how do I fix that?
.
def isPrime(N):
i = 2
while i**2 <= N:
if N % i == 0:
return False
i+=1
return True
for i in range(3, 21 + 1):
if isPrime(i):
print(i, 'is prime')
else:
print(i, 'is not a prime number')
First of all, create a function for determining whether or not a given number is prime (this is not a requirement but just a good practice). That function is not that hard: it just starts at i = 2 (starting at 1 makes no sense because every number can be divided by it) and check if N can be divided by it. If that is the case, we have found a divisor of N and thus, it isnt prime. Otherwise, continue with the next number: i += 1. The most tricky part of the loop is the stoping condition: i**2 <= N: we dont have to look further, because if some j > i is a divisor of N, then there is some other k < i that is also a divisor of N: k * j == N. If such k exists, we will find it before getting to the point where i * i == N. Thats all. After that, just iterate over each number you want to check for primality.
Btw, the best way to check for the primality of a set of number is using the Sieve of Eratosthenes
Your code only checks if a number is even. All odd numbers are not prime. So write a for-loop that checks if a odd number is divisible by any of the odd number less than that. Sometying like:
For i in (3 to n): If n mod i == 0, n is not prime.
I need to write a code that will find all prime numbers in a range of numbers and then list them in order saying which are prime and which are not, and also if they are not prime, show by what numbers they are divisible. It should look something like this:
>>> Prime(1,10)
1 is not a prime number
2 is a prime number
3 is a prime number
4 is divisible by 2
5 is a prime number
6 is divisible by 2, 3
7 is a prime number
8 is divisible by 2, 4
9 is divisible by 3
so far I have this which will only identify what numbers are prime and print them in a list. I don't know how to do the non prime numbers and to print what numbers it is divisible by. Also I get that 1 is a prime number.
def primeNum(num1, num2):
for num in range(num1,num2):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
print (num,'is a prime number')
Using a sieve will do the trick:
Example:
from __future__ import print_function
def primes():
"""Prime Number Generator
Generator an infinite sequence of primes
http://stackoverflow.com/questions/567222/simple-prime-generator-in-python
"""
# 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
def factors(n):
yield 1
i = 2
limit = n**0.5
while i <= limit:
if n % i == 0:
yield i
n = n / i
limit = n**0.5
else:
i += 1
if n > 1:
yield n
def primerange(start, stop):
pg = primes()
p = next(pg)
for i in xrange(start, stop):
while p < i:
p = next(pg)
if p == i:
print("{0} is prime".format(i))
else:
print("{0} is not prime and has factors: {1}".format(i, ", ".join(map(str, set(factors(i))))))
Output:
>>> primerange(1, 10)
1 is not prime and has factors: 1
2 is prime
3 is prime
4 is not prime and has factors: 1, 2
5 is prime
6 is not prime and has factors: 1, 2, 3
7 is prime
8 is not prime and has factors: 1, 2
9 is not prime and has factors: 1, 3
Just add a print and a break at the position where you set prime to false.
A more elegant solution would be to make a separate function isPrime or to use break and else in the inner for loop. Either way would make prime unnecessary.
You can only divide one by one and itself so it is a prime number, by that definition at least.
you could store the divisors for each number on a list and then print it with ", ".join(yourList)
i.e:
def primeNum(num1, num2):
for num in range(num1,num2):
divisors = []
for i in range(2,num):
if (num%i == 0):
divisors.append(str(i))
if divisors:
print ('%d is divisible by ' %num + ', '.join(divisors))
else:
print ('%d is a prime number' %num)
Edit: dumb syntax error
> # Check a number whether prime or not
a = int(input("Please your number (>1): "))
y = 2
import math
b = math.floor(math.sqrt(a)) + 1
x = True
while x:
if a == 2:
print(f'{a} is prime')
x = False
else:
x = True
if a %y == 0:
print(f' {a} is not prime')
x = False
else:
y = y + 1
if y >= b:
print(f'{a} is prime')
x = False
else:
x = True
Here is the Simple program for the output
def isPrime(lower,upper):
for num in range(lower,upper+1):
if num > 1:
for i in range(2,num):
if (num % 1) == 0:
break
else:
print(num," is a prime number")
def isDivisible(lower,upper):
for num in range(lower,upper+1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num," is divisible by ", i)
else:
pass
else:
pass
Lower = int(input("Enter your Lower limit"))
Upper = int(input("Enter Your Upper Limit"))
isPrime(Lower,Upper)
isDivisible(Lower,Upper)
**This is the output to code:**
2 is a prime number
4 is divisible by 2
6 is divisible by 2
6 is divisible by 3
8 is divisible by 2
8 is divisible by 4
9 is divisible by 3
10 is divisible by 2
10 is divisible by 5
isPrime() function will check whether the number is prime or not
isDivisible() function will check whether the number is divisible or not.
This piece of code receives a number from the user and determines whether it is prime or not. I can say that it is the fastest because in mathematics, to find out whether a number is prime or not, it is enough to examine the square root of that number.
import math
prime = int(input("Enter your number: "))
count = 0
sqr = int(math.sqrt(prime))
for i in range(2, sqr+1):
if prime % i == 0:
print("your number is not prime")
count += 1
break
if count == 0:
print("your number is prime")
The prime factors of 13195 are 5, 7, 13 and 29. What is the largest
prime factor of the number 600851475143 ?
Ok, so i am working on project euler problem 3 in python. I am kind of confused. I can't tell if the answers that i am getting with this program are correct or not. If somone could please tell me what im doing wrong it would be great!
#import pdb
odd_list=[]
prime_list=[2] #Begin with zero so that we can pop later without errors.
#Define a function that finds all the odd numbers in the range of a number
def oddNumbers(x):
x+=1 #add one to the number because range does not include it
for i in range(x):
if i%2!=0: #If it cannot be evenly divided by two it is eliminated
odd_list.append(i) #Add it too the list
return odd_list
def findPrimes(number_to_test, list_of_odd_numbers_in_tested_number): # Pass in the prime number to test
for i in list_of_odd_numbers_in_tested_number:
if number_to_test % i==0:
prime_list.append(i)
number_to_test=number_to_test / i
#prime_list.append(i)
#prime_list.pop(-2) #remove the old number so that we only have the biggest
if prime_list==[1]:
print "This has no prime factors other than 1"
else:
print prime_list
return prime_list
#pdb.set_trace()
number_to_test=raw_input("What number would you like to find the greatest prime of?\n:")
#Convert the input to an integer
number_to_test=int(number_to_test)
#Pass the number to the oddnumbers function
odds=oddNumbers(number_to_test)
#Pass the return of the oddnumbers function to the findPrimes function
findPrimes(number_to_test , odds)
The simple solution is trial division. Let's work through the factorization of 13195, then you can apply that method to the larger number that interests you.
Start with a trial divisor of 2; 13195 divided by 2 leaves a remainder of 1, so 2 does not divide 13195, and we can go on to the next trial divisor. Next we try 3, but that leaves a remainder of 1; then we try 4, but that leaves a remainder of 3. The next trial divisor is 5, and that does divide 13195, so we output 5 as a factor of 13195, reduce the original number to 2639 = 13195 / 5, and try 5 again. Now 2639 divided by 5 leaves a remainder of 4, so we advance to 6, which leaves a remainder of 5, then we advance to 7, which does divide 2639, so we output 7 as a factor of 2639 (and also a factor of 13195) and reduce the original number again to 377 = 2639 / 7. Now we try 7 again, but it fails to divide 377, as does 8, and 9, and 10, and 11, and 12, but 13 divides 2639. So we output 13 as a divisor of 377 (and of 2639 and 13195) and reduce the original number again to 29 = 377 / 13. As this point we are finished, because the square of the trial divisor, which is still 13, is greater than the remaining number, 29, which proves that 29 is prime; that is so because if n=pq, then either p or q must be less than, or equal to the square root of n, and since we have tried all those divisors, the remaining number, 29, must be prime. Thus, 13195 = 5 * 7 * 13 * 29.
Here's a pseudocode description of the algorithm:
function factors(n)
f = 2
while f * f <= n
if f divides n
output f
n = n / f
else
f = f + 1
output n
There are better ways to factor integers. But this method is sufficient for Project Euler #3, and for many other factorization projects as well. If you want to learn more about prime numbers and factorization, I modestly recommend the essay Programming with Prime Numbers at my blog, which among other things has a python implementation of the algorithm described above.
the number 600851475143 is big to discourage you to use brute-force.
the oddNumbers function in going to put 600851475143 / 2 numbers in odd_list, that's a lot of memory.
checking that a number can be divided by an odd number does not mean the odd number is a prime number. the algorithm you provided is wrong.
there are a lot of mathematical/algorithm tricks about prime numbers, you should and search them online then sieve through the answers. you might also get to the root of the problem to make sure you have squared away some of the issues.
you could use a generator to get the list of odds (not that it will help you):
odd_list = xrange(1, number+1, 2)
here are the concepts needed to deal with prime numbers:
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
http://en.wikipedia.org/wiki/Primality_test
if you are really stuck, then there are solutions already there:
Project Euler #3, infinite loop on factorization
Project Euler 3 - Why does this method work?
Project Euler Question 3 Help
Here is my Python code:
num=600851475143
i=2 # Smallest prime factor
for k in range(0,num):
if i >= num: # Prime factor of the number should not be greater than the number
break
elif num % i == 0: # Check if the number is evenly divisible by i
num = num / i
else:
i= i + 1
print ("biggest prime number is: "+str(num))
'''
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
'''
import math
def isPrime(x):
if x<2:
return False
for i in range(2,int(math.sqrt(x))):
if not x%i:
return False
return True
def largest_factor(number):
for i in range (2, int(math.sqrt(number))):
if number%i == 0:
number = number/i
if isPrime(number) is True:
max_val = number
break
print max_val
else:
i += 1
return max_val
largest_factor(600851475143)
This actually compiles very fast. It checks for the number formed for being the prime number or not.
Thanks
Another solution to this problem using Python.
def lpf(x):
lpf=2
while (x>lpf):
if (x%lpf==0):
x=x/lpf
else:
lpf+=1
return x
print(lpf(600851475143))
i = 3
factor = []
number = 600851475143
while i * i <= number:
if number % i != 0:
i += 2
else:
number /= i
factor.append(i)
while number >= i:
if number % i != 0:
i += 2
else:
number /= i
factor.append(i)
print(max(factor))
Here is my python code
a=2
list1=[]
while a<=13195: #replace 13195 with your input number
if 13195 %a ==0: #replace 13195 with your input number
x , count = 2, 0
while x <=a:
if a%x ==0:
count+=1
x+=1
if count <2:
list1.append(a)
a+=1
print (max(list1))
Here is my python code:
import math
ma = 600851475143
mn = 2
s = []
while mn < math.sqrt(ma):
rez = ma / mn
mn += 1
if ma % mn == 0:
s.append(mn)
print(max(s))
def prime_max(x):
a = x
i = 2
while i in range(2,int(a+1)):
if a%i == 0:
a = a/i
if a == 1:
print(i)
i = i-1
i = i+1