Help us understand the problem. What is going on with this article?

Pythonで因数分解

More than 3 years have passed since last update.

自然数 $n$ $(n\geq2)$ をPythonで因数分解します。

関数 factorization()

factorization.py
def factorization(n):
    if n > 1 and n % 1 == 0:
        for i in range(2, int(n**0.5)+1):
            if n % i == 0:
                print("%d = %i"%(n,i),end="")
                m = n // i
                j = 2
                while j <= m:
                    if m % j == 0:
                        print("*%d"%j,end="")
                        m = m // j
                        j = 2
                    else:
                        j += 1
                break
        else:
            print("%d is a prime number"%n,end="")
    else:
        print("error",end="")
    print()

実行

合成数

>>> factorization(18)
18 = 2*3*3

素数

>>> factorization(97)
97 is a prime number

自然数でない場合、「error」が返されます。

>>> factorization(-3)
error
>>> factorization(2.1)
error

最後に

>>> for x in range(2,21):
...     factorization(x)
...
2 is a prime number
3 is a prime number
4 = 2*2
5 is a prime number
6 = 2*3
7 is a prime number
8 = 2*2*2
9 = 3*3
10 = 2*5
11 is a prime number
12 = 2*2*3
13 is a prime number
14 = 2*7
15 = 3*5
16 = 2*2*2*2
17 is a prime number
18 = 2*3*3
19 is a prime number
20 = 2*2*5
xuyun19840618
横浜国立大学大学院 博士課程修了 時系列研究 マルチンゲール、AR過程、単位根逐次検定
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした