Prime Factorization [duplicate] - python

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]

Related

What is going wrong in this sum divisors program? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 months ago.
Improve this question
function should return the sum of all the divisors of a number, without including it. A divisor is a number that divides into another without a remainder. so for this I have written below function in python.
def sum_divisors(n):
k = 1
sum = 0
while k < n :
if n % int(k) == 0:
print(k)
sum = sum + int(k)
k += 1
k = k + 1
# Return the sum of all divisors of n, not including n
return sum
print(sum_divisors(0)) # 0
print(sum_divisors(3)) # Should sum of 1 # total 1
print(sum_divisors(36))
print("----------") # Should sum of 1+2+3+4+6+9+12+18 # total 55
print(sum_divisors(102))
print("----------") # Should be sum of 2+3+6+17+34+51 # total 114
But I am getting o/p as --> 0 , 1 49, 112 respectively for above function.
after analysis I found that - value of "k" is not getting incremented inside if block as 2 and 4.
K value is comming as below for above four functioned when getting called-->
0
----------
1
1 --> it should be 2
----------
1 --> after 1 next should come as 2 , as 36 is divisible by 2
3 --> after 3 next should come as 4 , as 36 is divisible by 4, but it is missing
6
9
12
18
49
----------
1 --> after 1 next should come as 2 , as 102 is divisible by 2
3
6
17
34
51
112
so can anyone please tell what is going wrong above. If possible you can suggest any alternate method to optimize above program.
You're incrementing k twice, once conditionally inside the if, once unconditionally outside it, so you can never find adjacent factors. Remove the one inside the if.
Better, just replace it with a for+range loop and stop managing k manually:
def sum_divisors(n):
sum = 0
for k in range(1, n):
if n % k == 0: # No need to int-ify k, it's always an int anyway
print(k)
sum += k # Can use += to avoid repetition, and k is an int already
# Return the sum of all divisors of n, not including n
return sum
If the print is purely for debugging and can be removed, this simplifies to a one-liner, with the optimized sum function + a generator expression:
def sum_divisors(n):
return sum(k for k in range(1, n) if n % k == 0)
you only have to comment the first addition of k :
it is as if you're incrementing it twice so you're jumping on numbers to test on.
def sum_divisors(n):
k = 1
sum = 0
while k < n :
if n % int(k) == 0:
# print(k)
sum = sum + int(k)
# k += 1
k = k + 1
# Return the sum of all divisors of n, not including n
return sum
print(sum_divisors(0)) # 0
print(sum_divisors(3)) # Should sum of 1 # total 1
print(sum_divisors(36))
print("----------") # Should sum of 1+2+3+4+6+9+12+18 # total 55
print(sum_divisors(102))
print("----------") # Should be sum of 2+3+6+17+34+51 # total 114
You have both k += 1 and k = k + 1 inside your loop, so that means that you add 2 for every iteration.
This code:
def sum_divisors(n):
k = 1
sum = 0
while k < n :
if n % int(k) == 0:
print(k)
sum = sum + int(k)
k = k + 1
# Return the sum of all divisors of n, not including n
return sum
print(sum_divisors(0)) # 0
print("----------")
print(sum_divisors(3)) # Should sum of 1 # total 1
print("----------")
print(sum_divisors(36))
print("----------") # Should sum of 1+2+3+4+6+9+12+18 # total 55
print(sum_divisors(102))
print("----------") # Should be sum of 2+3+6+17+34+51 # total 114
Gives this output:
0
----------
1
1
----------
1
2
3
4
6
9
12
18
55
----------
1
2
3
6
17
34
51
114
----------
You have to use "else" for k = k + 1
def sum_divisors(n):
k = 1
sum = 0
print(n)
while k < n :
if n % k == 0:
print(k)
sum = sum + k
k += 1
else:
k = k + 1
return sum

Why does program count one extra value (cycle "while")?

Why the program count one more value? For example, I give him N = 50. It gives out:
1
4
9
16
25
36
49
64
Code:
N = int(input())
n = 1
k = 1
while n < N:
n = k ** 2
print(n)
k = k + 1
As explained, you're checking n then changing n, you want to change n then check before continuing.
You can use the walrus operator to assign n and check it's value all in the while statement. (requires Python 3.8+)
N = int(input())
n = 1
k = 1
while (n := k**2) < N:
print(n)
k += 1
This essentially assigns n to k**2 then checks if that result is <N before continuing.
1
4
9
16
25
36
49
Your program outputs 1 4 9 16 25 36 49 64 if your input is 50 because the `while`` loop is checking the value before you increase it. Once in the loop, you increase it, calculate the square and then print.
If you want it to terminate, try setting calculating n as the last step in the loop:
N = int(input())
n = 1
k = 1
while n < N:
print(n)
k = k + 1
n = k ** 2
You're checking whether you reached the limit before you calculate the square and print it. So you're checking the previous value of n, not the one that's about to be printed.
Move the check inside the loop.
while True:
n = k ** 2
if n >= N:
break
print(n)
k += 1
The n < N is evaluated after you've changed (and printed) n.
n = 1
k = 1
N=50
while 1:
n = k ** 2
if n > N:
break
print(n)
k = k + 1
To fix this, break before you print, moving the evaluation inside the loop rather than after the last update of n
1
4
9
16
25
36
49
With the condition of your code, for example, when n = 49, The condition is fulfilled because 49 < 50 therefore it will continue to process the value and print the new one. But once n = 64 which is > 50, it stops. This is a possible solution:
N = int(input())
n = 1
k = 1
while True:
if n >= N:
break
n = k ** 2
print(n)
k = k + 1
This will continuously execute the code but once the condition is met that n >= N, it will stop executing.

Time limit exceeded python while uploading on stepik

The task is: introduced 2 numbers N(0-10000) - number of components, Q - number of requests. Then inputs N numbers of tests results. And then input Q numbers. Need to summarize an amount of all numbers in N which are less then Q
Sample Input:
10 3
2 6 8 4 5 1 9 0 3 7
3
8
0
Sample Output:
6
36
0
Made this task. If i m doing it local, with other random numbers it works. When i m trying to upload it on the stepik task I`ve got timelimit exceeded.
N, Q = input().split()
N = int(N)
Q = int(Q)
problems = input().split()
numMis = [0]*Q
MB = [0]*Q
if N > 0 or Q > 0:
for i in range(Q):
numMis[i] = int(input())
for i in range(Q):
for j in range(N):
if numMis[i] >= int(problems[j]):
MB[i] += int(problems[j])
for i in range(Q):
print(MB[i])
else:
print('0')

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

find all prime numbers from given range 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")

Categories