find all prime numbers from given range python - python

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

Related

My output keeps on repeating itself? (Python)

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

A for loop to print dictionary items once without repeating the print function

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

Beginner creating fizzbuzz function

This code is supposed to output fizz if number is divisible by 3, buzz if divisible by 5 and fizzbuzz if divisible by 3 and 5. Although I'm a bit unfamiliar with defining my own function and using the return appropriately. How do I remove the last 16 if the user inputs the number 16?
number = int(input("Enter a number: "))
def fizzbuzz(number):
n = 1
while n <= number:
if n % 3 != 0 and n % 5 != 0:
print(n)
elif n % 3 == 0 and n % 5 == 0:
print("fizzbuzz")
elif n % 3 == 0:
print("fizz")
elif n % 5 == 0:
print("buzz")
n = n + 1
return number
print(fizzbuzz(number))
If number = 16 it outputs
Enter a number: 16
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
16
How do I get I remove the last number 16, as it isn't supposed to be there
print("buzz")
n = n + 1
return number
print(fizzbuzz(number))
Here's your problem. Don't return the number, and don't print the return value of the function.
print("buzz")
n = n + 1
fizzbuzz(number)

Prime Factorization [duplicate]

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]

Python: Wrong output and ValueError: Prime Factors Creator

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.

Categories