Q. Write a program to display all of the integers from 1 up to and including some integer entered by the user followed by a list of each number's prime factors. Numbers greater than 1 that only have a single prime factor will be marked as prime.
For example, if the user enters 10 then the output of the program should be:
Enter the maximum value to display: 10
1 = 1
2 = 2 (prime)
3 = 3 (prime)
4 = 2x2
5 = 5 (prime)
6 = 2x3
7 = 7 (prime)
8 = 2x2x2
9 = 3x3
10 = 2x5
You can understand by Watching video :-
Answer =
num = int(input("Enter a number :-")) print("1 = 1 \n2 = 2(prime)") for i in range(3,num+1): print(i ,end=" = ") prime = 0 multiply = 1 factor = "" number = i for j in range(2,i): while number % j == 0: prime = 1 multiply *= j if multiply > i : break else : factor+= str(j)+"x" number = number // j if multiply > i : break print(factor[:-1],end="") if prime == 0: print(i,"(prime)",end="") print()
Output :-
Enter a number :-10
1 = 1
2 = 2(prime)
3 = 3 (prime)
4 = 2x2
5 = 5 (prime)
6 = 2x3
7 = 7 (prime)
8 = 2x2x2
9 = 3x3
10 = 2x5
Thanks a lot��
ReplyDeleteWelcome : )
DeletePlease attach video solution for this question
ReplyDeleteYes, very soon.
Deleteyes the code is ok but it is not generalised . Suppose if somebody enters 1 then only "1=1" should be printed but in your case "2=2(prime)" will also printed.
ReplyDeleten = int(input("Enter a limit: "))
pf = []
def prime(a):
c = 0
for i in range(1, a + 1):
if a % i == 0:
c += 1
if c == 2:
return a
else:
return 1
for i in range(2, n + 1):
if prime(i) == i:
pf.append(i)
l = len(pf)
if n >= 1: print("1==1")
for i in range(2, n + 1):
if prime(i) == i:
print(i, "=", i, "(prime)")
else:
print(i, end=" = ")
a = []
var = i
for k in range(0, l):
while var % pf[k] == 0:
a.append(pf[k])
var /= pf[k]
l1 = len(a)
for y in range(0, l1 - 1):
print(a[y], end=" x ")
print(a[l1 - 1])
This code will work for all values but it is done with the use of functions .. Hppy coding
Why are such spaces given in between ? Is it mandatory ?
ReplyDeleteNo, This space is not necessary.
DeletePost a Comment
You can help us by Clicking on ads. ^_^
Please do not send spam comment : )