I've created a program that successfully detects whether a number is prime, or not, it also will return a list of the factors of the number if it isn't, but that part is not successful.
Here is my code:
def prime_num():
num = int(input("Give me a number...: "))
prime = True
if num == 1:
prime = False
elif num == 2:
prime = True
for x in range(2, num):
if num % x == 0:
prime = False
break
if prime == False:
print("That's not a prime number!")
factors(num)
elif prime == True:
print("That's a prime number!")
def factors(num):
factors = []
for x in range(1, num+1):
if num % x == 0:
factors.append(x)
print("The factors for " + str(num) + " are: ", factors)
for x in factors:
for y in range(1, x):
if x % y == 0:
factors.remove(x)
print("The prime factors for " + str(num) + " are: ", factors)
When I use this function with a "num" value of 25 I get this output...
prime_num()
Give me a number...: 25
That's not a prime number!
The factors for 25 are: [1, 5, 25]
The prime factors for 25 are: [1, 25]
Which isn't the correct output for prime factors, I just want it to return: [5]
(I'm not concerned about the multiplicity of the factors at this time)
However, when I try the number 50, as my "num". I get this output with a valueError:
prime_num()
Give me a number...: 50
That's not a prime number!
The factors for 50 are: [1, 2, 5, 10, 25, 50]
Traceback (most recent call last):
File "<ipython-input-19-12c785465e2a>", line 1, in <module>
prime_num()
File "C:/Users/x/Desktop/Python/Python Practice/primes.py", line 25, in prime_num
factors(num)
File "C:/Users/x/Desktop/Python/Python Practice/primes.py", line 40, in factors
factors.remove(x)
ValueError: list.remove(x): x not in list
I realize this means somehow my x isn't in factors, but I'm not sure how considering I'm specifically iterating through factors.
This should make it clear what your problem is:
factors = [1,5,25]
for x in factors:
for y in range(1,x):
print x,y
5 1
5 2
5 3
5 4
25 1
25 2
25 3
25 4
25 5
25 6
25 7
25 8
25 9
25 10
25 11
25 12
25 13
25 14
25 15
25 16
25 17
25 18
25 19
25 20
25 21
25 22
25 23
25 24
You're iterating over your factors in such a way that you ignore 1 and ignore the x % x combination. range(1,1) is the empty list, and then you simply stop short because you've increased the start point by 1 (from zero) but not the end point, leaving what you iterate over too short.
The reason you get a ValueError is because any non-square number (ie, not 4, 9, 16, 25, etc.) will be removed twice. For 6, for example, it will remove for the 2,3 combo and when it gets to the 3,2 combo it's already been removed, thus the error. One way to fix this is to make the code only go halfway minus one to your total, so that inverted numbers aren't removed twice. For example, stop at 2 for 6, 4 for 10, etc.
Related
so i'm creating this function that gets a user to input a number greater than 2.
The code should then print all the prime numbers starting from 2 and ending at the number the user inputted.
So here is my code and it works (yay!)
def enterNumber():
number = int(input("Enter a number greater than 2"))
lower = 2
upper = number
for number in range (lower, upper):
if number > 2:
for i in range (2, number):
if (number % i) == 0:
break
else:
if (number % i) != 0:
print(number)
enterNumber()
BUT here is my output if the user inputs 18
"Enter a number greater than 2"
user puts "18"
output: 3
5
5
5
7
7
7
7
7
9
11
11
11
11
11
11
11
11
11
13
13
13
13
13
13
13
13
13
13
13
15
17
17
17
17
17
17
17
17
17
17
17
17
17
17
17
why is my output repeating itself? Any suggestions would be greatly appreciated thanks!
Your problem is here:
for i in range (2, number):
if (number % i) == 0:
break
else:
if (number % i) != 0:
print(number)
The else being inside the loop, says that you're going to print the number every time you find a non-divisor. For instance, for number = 11, you will print 11 for i values 2-10.
You don't know whether the number is a prime until you are done with the loop. Your print has to go after the loop, on a normal exit. An often-forgotten language feature is that a loop can have an else for exactly this purpose.
for i in range (2, number):
if (number % i) == 0:
break
else:
print(number)
Output:
Enter a number greater than 218
3
5
7
11
13
17
A simple solution(there are better ways):
def enterNumber():
number = int(input("Enter a number greater than 2"))
lower = 2
upper = number
for number in range(lower, upper):
prime = True
for i in range(2, number):
if (number % i) == 0:
prime = False
break
if prime:
print(number)
enterNumber()
I am new to Python and Stackoverflow in general, so sorry if my formatting sucks and i'm not good at enlish.But i have a problem with this code.
print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
for n in range(1, n + 1):
if n >= 1:
for i in range(2, n):
if (n % i) == 0:
break
else:
print('They are',n,end=' ')
The result of the code when ran comes out looking like this:
Displays prime numbers from 1 to N.
Please enter a value of n:40
They are 1 They are 2 They are 3 They are 5 They are 7 They are 11 They are 13 They are 17 They are 19 They are 23 They are 29 They are 31 They are 37
but i want it like this:
Displays prime numbers from 1 to N.
Please enter a value of n:40
They are 1 2 3 5 7 11 13 17 19 23 29 31 37
If you're completely determined not to use the print function more than once inside the loop, you could set a flag to determine whether to print the first two words. Like so:
print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
first = 'They are '
for n in range(1, n + 1):
if n >= 1:
for i in range(2, n):
if (n % i) == 0:
break
else:
print(first + str(n), end=' ')
if len(first) > 0:
first = ''
The following solution may help you
print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
num = [] # Create empty list
for n in range(1, n + 1):
if n >= 1:
for i in range(2, n):
if (n % i) == 0:
break
else:
num.append(n)
# Write the print statement outside of the loop and use .join() function and for loop
#to print each element of the list look like the output you have posted
#
print('They are'," ".join(str(x) for x in num))
Output:
Displays prime numbers from 1 to N.
Please enter a value of n: 40
They are 1 2 3 5 7 11 13 17 19 23 29 31 37
Output should be as follows:
Give the lower bound of the number range: 0
Give the upper bound of the number range: 1
0 cannot be prime.
1 cannot be prime.
Could not find primes from the test range.
Give the lower bound of the number range: 0
Give the upper bound of the number range: 20
0 cannot be prime.
1 cannot be prime.
2 is a prime.
3 is a prime.
4 is not a prime, because 2 * 2 = 4
5 is a prime.
6 is not a prime, because 2 * 3 = 6
7 is a prime.
8 is not a prime, because 2 * 4 = 8
9 is not a prime, because 3 * 3 = 9
10 is not a prime, because 2 * 5 = 10
11 is a prime.
12 is not a prime, because 2 * 6 = 12
13 is a prime.
14 is not a prime, because 2 * 7 = 14
15 is not a prime, because 3 * 5 = 15
16 is not a prime, because 2 * 8 = 16
17 is a prime.
18 is not a prime, because 2 * 9 = 18
19 is a prime.
20 is not a prime, because 2 * 10 = 20
Searched 21 numbers, from which 8 were primes.
The last found prime was 19.
low = input("Give the lower bound of the number range: ")
high = input("Give the upper bound of the number range: ")
low = int(low)
high = int(high)
for n in range(low,high):
if n<2:
print (n, "cannot be prime.")
for n in range(low,high):
for x in range (2, n):
if n % x == 0: # is n divisible with x? If yes, not a prime
y = n//x*x
print(n, "is not a prime, because", x, "*", n//x, "=", y)
break #this breaks the inner loop, and we continue with the outer!
else:
print(n, "is a prime.")
break
The code is not successfully running
It shows the output:
Give the lower bound of the number range: 0↩
Give the upper bound of the number range: 20↩
0 cannot be prime.↩
1 cannot be prime.↩
3 is a prime.↩
4 is not a prime, because 2 * 2 = 4↩
5 is a prime.↩
6 is not a prime, because 2 * 3 = 6↩
7 is a prime.↩
8 is not a prime, because 2 * 4 = 8↩
9 is a prime.↩
10 is not a prime, because 2 * 5 = 10↩
11 is a prime.↩
12 is not a prime, because 2 * 6 = 12↩
13 is a prime.↩
14 is not a prime, because 2 * 7 = 14↩
15 is a prime.↩
16 is not a prime, because 2 * 8 = 16↩
17 is a prime.↩
18 is not a prime, because 2 * 9 = 18↩
19 is a prime.
You are not checking if n is divisible by all numbers between 2 and n, since you exit the inner for loop after the first iteretion in both cases (when n divisible by x and when it is not).
To fix it, you need to move the else block to the outer loop (so it will run only when you don't exit the loop, meaning n is prime), and only break when n is not prime.
low = input("Give the lower bound of the number range: ")
high = input("Give the upper bound of the number range: ")
low = int(low)
high = int(high)
for n in range(low,high):
if n<2:
print (n, "cannot be prime.")
for n in range(low,high):
for x in range (2, n):
if n % x == 0: # is n divisible with x? If yes, not a prime
y = n//x*x
print(n, "is not a prime, because", x, "*", n//x, "=", y)
break #this breaks the inner loop, and we continue with the outer!
else:
print(n, "is a prime.")
try to use this one works for 0-20 range
low = input("Give the lower bound of the number range: ")
high = input("Give the upper bound of the number range: ")
low = int(low)
high = int(high)
for n in range(low, high+1):
if n <= 1:
print(n, "cannot be prime")
elif n == 2 or n == 3:
print(n, "is a prime")
elif n % 2 == 0 or n % 3 == 0:
print(n, "is not a prime")
else:
print(n, "is a prime")
I've recently started learning Python. I was doing some exercises on the Control Structures section of the course and everything was going fine until I got stumped on the last problem. I've been looking at it for three days now, and I'm pretty sure that the solution is quite obvious. Here is a description in the exercise:
Start with any number. If the number is divisible by 3, divide it by
3. Otherwise, add 2 to the number. Eventually, no matter what number you begin with, this series will run into 1. For example, imagine we
started with the number 5: 5 is not divisible by 3, so 5 + 2 = 7 7 is
not divisible by 3, so 7 + 2 = 9 9 is divisible by 3, so 9 / 3 = 3 3
is divisible by 3, so 3 / 3 = 1
Start with 5, this sequence converges on 1 in 4 iterations: 5 -> 7, 7
-> 9, 9 -> 3, 3 -> 1.
Write a function called joyner. joyner should have one parameter, an
integer. It should return the number of iterations required to reach 1
for the first time.
I ran the function I wrote on a page that tests my function with different integers. Every time it gave me an error (saying how many iterations were expected and how many my program calculated) I managed to fix the program for that integer, but the following integer tested would give me an error again. The code is below is the final re-write before I decided to come here to ask for help.
def joyner(num):
count = 0
while num % 3 != 0:
# print("num not divisible by 3")
num = num + 2
# print("added 2")
count += 1
# print(count)
if num % 3 == 0:
# print("num is divisible by 3")
num /= 3
# print("divided by 3")
count += 1
# print(count)
while num % 3 == 0:
# print("num is divisible by 3")
num /= 3
# print("divided by 3")
count += 1
# print(count)
return count
Here are the results:
We found the following problems with your submission:
We tested your code with num = 15. We expected joyner to return the
int 5. However, it returned the int 1.
We tested your code with num = 29. We expected joyner to return the
int 10. However, it returned the int 3.
We tested your code with num = 65. We expected joyner to return the
int 8. However, it returned the int 3.
We tested your code with num = 12. We expected joyner to return the
int 3. However, it returned the int 1.
We tested your code with num = 32. We expected joyner to return the
int 6. However, it returned the int 4.
Note that these errors may have prevented us from checking your
submission in other ways, so fixing these problems may cause other
problems to show up next time. Keep trying! This is what debugging is
all about.
The following things were correct about your submission:
We expected to find a function named joyner in your code, and we did.
We tested your code with num = 5. We expected joyner to return the int
4, and it did.
We tested your code with num = 27. We expected joyner to return the
int 3, and it did.
We tested your code with num = 16. We expected joyner to return the
int 3, and it did.
The thing with your code is that it assumes that when a number is no longer divisible by 3 that it reached 1, that is regarding your second loop, for example 15 is divisible by 3, it becomes 5, which is not divisible but also not 1.
Overall think about it this way, a number may be either divisible or not at once, so it should happen in one loop, and you should stop when you reach 1.
The premise of your task is not correct:
Start with any number. If the number is divisible by 3, divide it by 3. Otherwise, add 2 to the number. Eventually, no matter what number you begin with, this series will run into 1.
number = 4
4 + 2 = 6 # 4 is not divisible by 3, add 2
6 / 3 = 2 # 6 is divisible by 3 -> 2
2 + 2 = 4 # 2 is not divisible by 3, add 2
4 + 2 = 6 # 4 is not divisible by 3, add 2 --> cycle - no solution.
If there is a solution, this finds it:
def joyner(num):
count = 0
seen = set()
while num != 1:
if num in seen:
return None
else:
seen.add(num)
if num % 3 == 0:
num = num // 3
else:
num += 2
count += 1
return count
Test it:
i = 0
for k,c in d.items():
if c is None:
continue
print(k,":",c, end=" ")
i += 1
if i % 6 == 0:
print()
i = 0
Output of solutions from 1 to 99:
1 : 0 3 : 1 5 : 4 7 : 3 9 : 2 11 : 7
13 : 6 15 : 5 17 : 6 19 : 5 21 : 4 23 : 5
25 : 4 27 : 3 29 : 10 31 : 9 33 : 8 35 : 9
37 : 8 39 : 7 41 : 8 43 : 7 45 : 6 47 : 9
49 : 8 51 : 7 53 : 8 55 : 7 57 : 6 59 : 7
61 : 6 63 : 5 65 : 8 67 : 7 69 : 6 71 : 7
73 : 6 75 : 5 77 : 6 79 : 5 81 : 4 83 : 13
85 : 12 87 : 11 89 : 12 91 : 11 93 : 10 95 : 11
97 : 10 99 : 9
Not viable:
[ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40,
42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78,
80, 82, 84, 86, 88, 90, 92, 94, 96, 98]
Your algo only works for odd numbers.
We tested your code with num = 12. We expected joyner to return the int 3. However, it returned the int 1.
does not work at all
This question already has answers here:
Prime factorization - list
(17 answers)
Closed 6 years ago.
So my program is supposed to find the prime factors of an integer and then the contents of the integer array is printed out and the values in the array are supposed to be multiplied together (giving you the original number)
this is what it is supposed to look like
Prime Factorization Program
Enter an integer > 1: 210
Prime Factors
2
3
5
7
Check Product = 210
this is my code and my results
def main():
a = [0]*20
print("Prime Factorization Program")
print()
num = eval(input("Enter an integer > 1: "))
count = 0
for k in range(1,num):
if num % k == 0:
a[count]= k
count = count + 1
mySum = 0
for k in range(count):
mySum = mySum + a[k]
print()
print("Prime Factors")
for k in range(count):
print(a[k])
print("Check Product =",mySum)
main()
here are my result
Prime Factorization Program
Enter an integer > 1: 210
Prime Factors
1
2
3
5
6
7
10
14
15
21
30
35
42
70
105
Check Product = 366
Problem - If f is a factor, you don't want to count multiples of f.
Solution - Once you identify a factor f, divide n by f.
Example - 210 is divisible by 2; divide by 2 and thereafter process 105. That ensures you don't count any more multiples of 2 like 6 or 10. 105 is divisible by 3; divide by 3 and continue with 35.
Problem - Prime factors can show up multiple times. 12 = 2×2×3.
Solution - If f is a factor, keep checking for it and dividing by f until you've accounted for all occurrences.
Example - 12 is divisible by 2; divide by 2 to get 6. 6 is still divisible by 2; divide by 2 again to get 3. 3 is not divisible by 2; continue to the next factor.
Because your code is printing all the factor instead of just prime factors. Below is the sample function you may refer for prime factorization:
def prime_factors(n):
prim_facs = []
d = 2
while d*d <= n:
while (n % d) == 0:
prim_facs.append(d)
n //= d
d += 1
if n > 1:
prim_facs.append(n)
return prim_facs
# Sample Example
# >>> prime_factors(210)
# [2, 3, 5, 7]