def prime_factors(n):
factors = []
while n % 2 == 0:
factors.append(2)
n //= 2
i = 3
while i <= n:
if n % i == 0:
factors.append(i)
n //= i
else:
i += 2
return factors
num = int(input("Enter a number: "))
factors = prime_factors(num)
print(f"Prime factors of {num} are: {factors}")
Code Explanation:
1. Function Definition
def prime_factors(n):
factors = []
A function named prime_factors is defined to calculate the prime factors of a number n.
An empty list factors is initialized to store the prime factors.
2. Handle Factor of 2 (Even Prime)
while n % 2 == 0:
factors.append(2)
n //= 2
This loop continuously divides n by 2 as long as it is divisible by 2.
Each time n is divisible by 2:
2 is added to the factors list.
n is updated to n // 2 (integer division).
After this step, n becomes an odd number because all factors of 2 are removed.
3. Handle Odd Factors
i = 3
while i <= n:
A variable i is initialized to 3 to check for odd factors.
The loop runs as long as i is less than or equal to n.
if n % i == 0:
factors.append(i)
n //= i
Inside the loop:
If n is divisible by i, it adds i to the factors list and updates n to n // i.
This process removes all occurrences of the factor i.
else:
i += 2
If n is not divisible by i, the next odd number (i + 2) is tested as a potential factor.
Only odd numbers are checked because all even factors are already removed.
4. Return the Factors
return factors
Once all factors are processed (i.e., n becomes 1), the function returns the list of prime factors.
5. User Input and Function Call
num = int(input("Enter a number: "))
The user is prompted to input an integer (num) for which the prime factors will be calculated.
factors = prime_factors(num)
print(f"Prime factors of {num} are: {factors}")
The prime_factors function is called with num as its argument.
The returned list of factors is stored in the variable factors and printed to the user.
#source code --> clcoding.com
0 Comments:
Post a Comment