so I’m trying to get the of a given number. The thing is, the code prints the wrong message and it also doesn’t work with all numbers. Why is that?
This is the part to get the factors:
thefactors = [] d = 2 while d*d <= number: while (number % d) == 0: factors.append(d) number //= d d += 1 break if number > 1: factors.append(number) print('The factors of {} are:'.format(number), thefactors)
What’s going on and how do I fix it?
Answer
The issue I see is that you are both checking that the square of d
is less than n
(d*d <= n
or d**2 <= n
) AND that you reassign n
when a factor is discovered (n //= d
). This is not including the unnecessary break
statement.
Here’s what I did:
>>> def factorization(n): factors = [] d = 2 while d <= n: if n % d == 0: factors.append(d) n //= d d = 2 else: d += 1 return factors >>> factorization(104) [2, 2, 2, 13] >>> factorization(9) [3, 3] >>>
This method implicitly checks that d**2
is less than or equal to n
, since, to satisfy the while
condition, n // d
must be less than or equal to d
, thus d**2
must be less than or equal to n
.
To print the prime factorization:
>>> num = 104 >>> factors = factorization(num) >>> print(f"The prime factors of {num} are {factors}") The prime factors of 104 are [2, 2, 2, 13] >>> print(f"The prime factors of {num} are {', '.join(factors)}") The prime factors of 104 are 2, 2, 2, 13