LoginSignup
2
4

More than 5 years have passed since last update.

Pythonで因数分解

Last updated at Posted at 2016-12-06

自然数 $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
2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4