0
How can ı list a number's prime factors.(Multiple of all prime factors in list is equal to the number)
#Ex:) Number=120 and ı would like to see [2,2,2,3,5]. #Ex:) Number=150 [2,3,5,5]. def prime_numbers(x): a=range(1,x+1) b=[i for i in a if x%i==0] if len(b)==2: return x else: return 0 def prime_factors_of_number(x): a=range(1,x+1) b=[prime_numbers(i) for i in a if prime_numbers(i)!=0] c=[i for i in b if x%i==0] return c If ı write 120 for x value, i get [2,3,5], but wanted result is [2,2,2,3,5]. How should ı change my code? Thanks...
4 odpowiedzi
+ 2
Please save your program in a Python code in the SoloLearn code playground, so that it is easier to reference line numbers and errors. For now, I will reference line numbers according to the following code.
https://code.sololearn.com/cC108HvzlvHt/?ref=app
So first of all, your code has an error on line 12. `b` is a list and `x` is an int, but you are doing x % b. Perhaps you wanted to do `x % i`
To achieve the output you want to achieve, you need to do that same thing we did in school for finding the prime factors of a number. That is, start with the smallest prime factor, keep dividing till the number is divisible by the smallest prime factor, and when it is not, move on to the next prime factor. [Answer to be continued. I reached the character limit]
+ 2
These are the steps you should follow:
1. First of all, remove line 11, 12 and 13. Although they work, they are still a bit senseless. There is no point in first finding all the prime numbers between 1 and x, and then filtering out the factors of x
2. Instead make a list, say `pfactors`. Then make a for loop that loops on the range 1 till x. Let the loop variable be called `num` for now.
3. If x is a factor of num, and num is a prime number, go to step 4. Else ignore the number
4. Append `num` to `pfactors`
5. Divide `x` by `num`. If `x` is still divisible by `num`, go back to step 4
When the for loop is over, return `pfactors`.
A suggestion, in the prime_numbers function, instead of returning `x` or 0, returning True or False makes more sense.
+ 1
c=[i for i in b if x%b==0]
This is giving me error as you are dividing a number with list so I don't know how you got [2,3,5] as output
0
in line 12, ı wrote x%i instead of x%b. Now my code wont give any error.