How to Calculate Prime Factors of an Integer by Python


In this example we will show how to calculate the prime factor(s) of a given integer in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

n = int(input("Please input an integer: "))
print("Its prime factors are: ")
for i in range(1, n+1):
    if n % i == 0:
        k = 0
        for j in range(1, i+1):
            if i % j == 0:
                k = k + 1
        if k == 2:
            print(i)

Output:

Please input an integer: 28
Its prime factors are: 
2
7

Please input an integer: 189
Its prime factors are: 
3
7
Subscribe
Notify of
guest
1 Comment
Inline Feedbacks
View all comments
Guseyn013
Guseyn013
3 years ago

I think it would be better if you add some comments to explain the steps. Thanks!