Removing multiples of a number from a list in Python - python

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)

Related

Checking for prime numbers: Any number is prime?

Hello dearest community,
I'm stuck on something very easy, I guess sometimes your just out of it. Anyhow, I wrote this to check for prime numbers:
num = int(input(""))
if num > 1:
for i in range(2, num-1):
if (num % i) == 0:
print(num, "is no Primenumber")
break
else:
print(i, "PRIME!!!")
(The original code doesn't print anything, but I had trouble with it, so I rewrote it for debugging purposes)
Anyway, it correctly identifies non prime numbers, but prints out this for prime numbers, lets say 7:
7
2 PRIME!!!
3 PRIME!!!
4 PRIME!!!
5 PRIME!!!
Use the below logic to find the number is prime or not. This is suited for python, as there is an else block for the for loop which gets exectued when the loop is not broken during execution which mean the number is prime.
if num > 1:
# Iterate from 2 to n / 2
for i in range(2, num//2):
# If num is divisible by any number between
# 2 and n / 2, it is not prime
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
Not the most performance conscious, but will get the job done and is simple.
n = input("Enter a number to check if it is prime [returns True or False]: ")
n = int(n)
if n < 2:
quit()
if all(n % i for i in range(2, n)):
print(n, "PRIME!!!")
If you are concerned with performance for larger numbers it is better to use square root over number flooring division 2. Any number that is a factor greater than the square root will also have 1 that is less.
Here's a common solution:
def check_for_prime(p_in):
is_prime = True
for n in range(2, int(p_in ** 0.5) + 1):
if p_in % n == 0:
is_prime = False
break
return is_prime
num = int(input(""))
if check_for_prime(num):
print(f'{num} is prime')
else:
print(f'{num} is not prime')
Without third-party module, you can easily perform it this way:
def is_prime(number):
return all(number % n for n in range(2, number))
This way, you check:
all division between the specified number, and any number between 2 and the one before the number
the trick is to consider the fact that if any number % n gives 0, which means it is a multiple, so it can't be a prime number, and you will get a result immediately

Verify which numbers are prime in the list

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!

How to find primes (Python)

I'm beginner in python programming and got stumpled on a Basic Question:
print the number of primes up to a given number.
For example the amount of primes before the number 100.
why my Code is not working? or what is wrong with my logic?
def count_prime(num):
newnumber = 0
for x in num:
if x%2 == 0:
newnumber = newnumber + 1
print(newnumber)
count_prime(100)
One very simple way (i.e. computationally slow) to test if a number is prime is to simply check if it can be divided by any other number.
def is_prime(n):
# If n is 0 or 1, it is not prime
if n <= 1:
return False
# Check every number between 2 and n-1
for i in range(2, n):
# If n is divisible by i, then the remainder will be zero
if n % i == 0:
return False
# Since n wasn't divisible by any other number, it must be prime
return True
To print all of the primes, you can then simply check each number.
for i in range(num):
if is_prime(i):
print(i)
This method will be very slow for large values of num. To see some much faster methods for checking the primality of a number you can have a look at this question.
num = int(input("Enter a number: "))
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")

find prime numbers in python

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")

Python prime number calculator

prime = [2]
while len(prime) <= 1000:
i=3
a = 0
for number in prime:
testlist= []
testlist.append(i%number)
if 0 in testlist:
i=i+1
else:
prime.append(i)
i=i+1
print(prime[999])
Trying to make a program that computes primes for online course. This program never ends, but I can't see an infinite loop in my code.
A prime number is a number that can only be divided by exclusively one and itself.
My logic is that if a number can be divided by prime numbers preceding it then it is not prime.
As the comments to your question pointed out, there is several errors in your code.
Here is a version of your code working fine.
prime = [2]
i = 3
while len(prime) <= 1000:
testlist = []
for number in prime:
testlist.append(i % number)
if 0 not in testlist:
prime.append(i)
i = i + 1
print prime
I haven't tested but you can create method like below:
def get_prime_no_upto(number):
start = 2
primes = list(range(start,number)).to_a
for no in range(start,number):
for num in range(start,no):
if ( no % num == 0) and (num != no):
primes.delete(no)
break
primes
and can use it like
print primeno(100)
cheers!
def prime_checker(number):
stop = False
prime = True
n = 2
while stop == False and n < number:
if (number) % n == 0:
prime = False
stop = True
n += 1
if prime == True:
print("It's a prime number.")
elif prime == False:
print("It's not a prime number.")
prime_checker(11)

Categories

Resources