Python - Counting how many factors a number has - python

I have been trying to make a 'Prime Number Checker' that looks like this:
Please enter a number: 7
The factors are:
1
7
7 is a prime number
Try again? Y
Enter a number: 6
The factors are:
1
2
3
6
6 is not a prime number
It has 6 factors
I am stuck on the very last portion, which counts how many factors a non-prime number has (listed as 'num_factors' in the code below). Thank you! *Edited for clarity.
def main():
num = int(input("Please enter an integer between 2 and 5,000: "))
def list_factors(x):
print("The factors of your number are: ")
for i in range(1, x + 1):
if x % i == 0:
print(i)
list_factors(num)
def is_prime(num):
if num>1:
for i in range(2,num):
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")
is_prime(num)
def num_factors(x):
for i in range(1, x + 1):
if x % i == 0:
list = []
print("It has", len(list), "factors")
num_factors(x)
print()
again=input("Try again? (y/n): ")
if again == "y":
print()
main()
else:
print("Bye!")
if __name__ == "__main__":
main()

I suggest you build a list of factors first, instead of iterating at each step.
def get_factors(n):
factors = []
for i in range(1, n+1):
if n % i == 0:
factors.append(i)
return factors
Now you can define your other functions in terms of the list of factors:
def is_prime(factors):
return len(factors) == 2
def num_factors(factors):
return len(factors)
If you want to make your implementation more efficient, I suggest you read up on prime factorization.

a=int(input("Enter number: "))
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print("Number is prime")
else:
print("Number isn't prime")

Change
def num_factors(x):
for i in range(1, x + 1):
if x % i == 0:
list = []
print("It has", len(list), "factors")
num_factors(x)
for
def num_factors(x):
list = []
for i in range(1, x + 1):
if x % i == 0:
list.append(x)
print("It has", len(list), "factors")
num_factors(num)
Your number is called num, not x. Then you should create the factor list outside the for loop and append each factor to the list.
As somebody recommended in the comments, you should print outside of the functions. Also you don't need to check for factors bigger than x//2. So I would recommend something like this:
def num_factors(x):
list = []
for i in range(1, x//2 + 1):
if x % i == 0:
list.append(x)
return facts
facts=num_factors(num)
print("It has", len(facts), "factors")

You were very close, the only adjustment would be that you would want to append those values that pass if x % i == 0 which can also be stated if not x % i: and you would want to move the empty list outside of your loop. then just return the length of that list.
def num_factors(non_prime):
l = []
for i in range(1, non_prime+1):
if not non_prime % i:
l.append(i)
return len(l)
print('It has {} factors'.format(num_factors(10)))
# It has 4 factors.
Future References:
Just to open you to why it would be important to explore built in functions, you could accomplish this using filter in one expression
def num_factors(non_prime):
return len(list(filter(lambda x: not non_prime % x, range(1, non_prime +1))))
As well as with list comprehension
def num_factors(non_prime):
return len([i for i in range(1, non_prime +1) if not non_prime % i])
You can find information on both at https://docs.python.org/3/

# input and validation integer number
try:
num = int(input(
"Please enter an integer number between 2 and 5,000 : "))
except ValueError:
print("Please enter an integer number between 2 and 5,000!!!")
# for check number.
# If number is prime it's true
# If number not prime it's false
# default is true
status = True
print("%d divided by %d" % (num, 1))
for i in range(2, int(num / 2)+1):
if num % i == 0:
status = False
print("%d divided by %d" % (num, i))
print("%d divided by %d" % (num, num))
if status:
print("%d is prime" % (num))
else:
print("%d is not prime" % (num))

If you would like to capture all the factors, you could use the sub below. If you give it a number like 1024, it returns a list of ten 2's (all the factors)
def main():
x = int(input('Enter a number to find the prime factors '))
primes = prime_factors(x)
print(primes)
def prime_factors(x):
factors = []
y = 2
while (y <= x):
while x % y != 0:
y += 1
x /= y
factors.append(y)
return factors
main()

Related

Prime number in Python

#Write your code below this line ๐Ÿ‘‡
def prime_checker(number):
for num in range (2, number):
if num % number == 0:
print("It is not a prime number")
else:
print("It is a prime number")
#Write your code above this line ๐Ÿ‘†
#Do NOT change any of the code below๐Ÿ‘‡
n = int(input("Check this number: "))
prime_checker(number=n)
How can I print a text that number is prime or not only once?
Fix
number % num == 0 and not num % number == 0
A number isn't prime the moment you find a number that doesn't divide it, but only when you have tested all and none divides it
Use for/else construction, it goes into else if no break has been used
def prime_checker(number):
for num in range(2, number):
if number % num == 0:
print("It is not a prime number")
break
else:
print("It is a prime number")
Note that this only fixes your way to do, but that isn't the optimal way to check if a numbre is a prime one, at least, ending range at square root of number, and directly verifying division by small numbers like 2,3,5,7
There are few mistakes in your code. I have modified them.
def prime_checker(number):
for num in range(2, number):
if number % num == 0:
print('Not prime')
return
print('Prime number')
# Write your code above this line ๐Ÿ‘†
# Do NOT change any of the code below๐Ÿ‘‡
n = int(input("Check this number: "))
prime_checker(number=n)
For loop is to check if any of the number starting from 2 is a factor of number or not.
First, a slightly more efficient prime check by
going until the sqrt of the number only
going in steps of 2
import math
def is_prime(n: int) -> bool:
if n in (2, 3, 5):
return True
if n < 2 or n % 2 == 0:
return False
for i in range(3, math.ceil(math.sqrt(n)), 2):
if n % i == 0:
return False
return True
Now you can wrap that function in yours
def prime_checker(n: int):
msg = "%d is prime" if is_prime(n) else "%d is not prime"
print(msg % n)
prime_checker(11)
# 11 is prime
I think it's good to check a number is prime or not
def is_prime(n):
st = "prime" # being prime status
for i in range(2,n):
if n % i == 0: # if number is prime
st = "not prime"
break;
return st
n = int(input("enter n: "))
print (is_prime(n))
You only need to change the end of your code
your function is true except for these lines:
if num % number == 0:
print("It is not a prime number")
else:
print("It is a prime number")
you should change these to:
st = "Prime"
if number % num == 0:
st = "not prime"
return st

Enter n different positive numbers. Calculate the average value of all prime numbers among them. [Python]

I need to do as the title suggests however I have ran into a problem. This is my code so far:
#Input
n = int(input('Enter n: '))
#Prime = 0
p = []
#Loopidty
for i in range(n):
#Ask user to input x
x = int(input('Enter a Number: '))
#Check if prime
if x < 2:
print('The number is not prime.')
else:
for n in range(2, x - 1):
if x % n == 0:
print('The number is not prime.')
break
else:
print('The number is prime.')
p.append(x)
#Answer
Answer = sum(p) / n
print('The answer is: ', Answer)
The issues is when I add the prime numbers to the list it only adds the first number and stops there, how do I combat this?
Many thanks
It's a good idea to break your code into smaller parts. We can create a function to check if a number is prime or not and check that it is correct. After that just add the rest of the code.
import math
def is_prime(x):
"""Check that a number `x``is prime"""
# You only need to go up to sqrt(x)
for n in range(2, int(math.sqrt(x) + 1)):
if x % n == 0:
return False
return True
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
sum = 0.0
num_entries = 0 # Number of prime numbers entered by the user
n = int(input('Enter n: '))
for i in range(n):
x = int(input('Enter a Number: '))
if is_prime(x):
sum += x
num_entries += 1
if num_entries == 0:
print("You didn't enter any prime number")
else:
print("The average of the entered prime numbers is ", sum / num_entries)

I want to convert these outputs to a list

I am a Python beginner.
I got a prime number within the specified range. However, I couldn't convert it to a list.
I also tried converting it to a string and back to a list.
import random
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
for num in range(lower,upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
Start with an empty list, and every time you find a prime number, append it to the list. Then you can print the list at the end:
nums = []
for num in range(lower,upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
nums.append(num)
print(nums)
Note that you only need to iterate up the square root of num, any factor beyond that can only have another factor which is less than it:
from math import sqrt
nums = []
for num in range(lower,upper + 1):
if num > 1:
for i in range(2, int(sqrt(num))):
if (num % i) == 0:
break
else:
nums.append(num)
print(nums)

Is there a way to print at which point for loops ended?

I have a little thing here which checks if a number is prime or not:
num = int(input("Choose a number: "))
for i in range(2, num):
if num % i == 0:
print("Not prime")
break
else: print("prime")
What I would like to add is the output on which number the foor loop ended, so which number is the smallest divisor of num
Example: for num = 8 it would be 2. For num = 21 it would be 3
How can I implement that?
you can try this:
for i in range(2, num):
if num % i == 0:
print(num, " is Not prime")
print("Smallest devisor of num is = ", i)
break
else:
print("prime")

Prime Numbers python

I'm a beginning programmer in python and have a question about my code I'm writing:
number = int(input("Enter a random number: "))
for num in range(1, number + 1) :
for i in range(2, num) :
if (num % i) == 0 :
break
else :
print(num)
break
When I run this program I also get 9, 15 21 as output. But these are not prime numbers.
What is wrong with my code?
Thanks!
With if (num % i) == 0: you go to the else block for every num, which is not a multiply of 2, as you start i with 2, thus printing num. I got all odd numbers printed with your code.
You can use something like this:
number = int(input("Enter a random number: "))
for num in range(1, number + 1):
prime = True
for i in range(2, num):
if (num % i) == 0:
prime = False
break
if prime:
print(num)
It sets prime to False when it encounters a divisor without rest.
the trouble is in your else: statement which has to run outside of the first loop. I recommend the following:
def isprime(num):
for i in range(2, num):
if (num % i) == 0:
return False
return True
for num in range(1, number + 1) :
if isprime(num):
print num
Your problem
The else statement that you put inside the for loop means that if that number(num) is divisible by this current no represented by i, return true considering it as a prime which IS NOT CORRECT.
Suggestion
Your outer loop starts with 1 which should change to 2, as 1 is not a prime number
Solution
def fun(number):
#Not counting 1 in the sequence as its not prime
for num in range(2, number + 1) :
isPrime = True
for i in range(2, num) :
if (num % i) == 0 :
isPrime = False
break
if isPrime:
print num
fun(10)
Output
1
2
3
5
7
I am assuming the random number is the range you want the numbers to be within.
I found that the variable i is always equal to 2 in your code.This destroys the purpose of having a second for loop
Prime numbers are numbers that cannot be divisible by 2, 3 or 7, excluding 2, 3 or 7!
With this knowledge I adapted your code to show the true prime numbers.
solution
number = int(input("Enter a random number: "))
for num in range(2,number +1) :
printnum = True
if num == 2:
printnum = True
elif num == 3:
printnum = True
elif num == 7:
printnum = True
elif num % 2 == 0:
printnum = False
elif num % 3 == 0:
printnum = False
elif num % 7 == 0:
printnum = False
if printnum == True:
print(num)
This is my method to generate first ten prime numbers with no imports, just simple code with components we are learning on college. I save those numbers into list.
def main():
listaPrim = []
broj = 0
while len(listaPrim) != 10:
broj+= 1
brojac = 0
for i in range(1,100):
if broj % i == 0:
brojac += 1
if brojac == 2:
listaPrim.append(broj)
print(listaPrim)
if __name__=='__main__':
main()

Categories