LoginSignup
1
1

More than 1 year has passed since last update.

指定した数を素因数分解した値を表示するコード

Last updated at Posted at 2022-09-25

指定した数を素因数分解した値を表示するコード

素因数分解.py
import tkinter as tk

def dispLabel():
    number= []
    a = int(EditBox.get())
    str_a = str(a)
    lbl2.configure(text = str_a + "=")

    while a!=1:
        for waruyatsu in range(2,a+1):
            if a%waruyatsu == 0:
                number.append(waruyatsu)
                number.append("×")
                a=int(a/waruyatsu)
                break

    number.pop(-1)
    lbl3.configure(text = number)

root = tk.Tk()
root.geometry("300x200")

EditBox = tk.Entry(width=6)
EditBox.place(x = 230, y = 20)

btn = tk.Button(text = "調べる", command = dispLabel).place(x = 60, y = 50)

lbl1 = tk.Label(text = "調べたい数字は何ですか?").place(x = 20, y = 20)
lbl2 = tk.Label(text = " ")
lbl2.place(x = 20, y = 80)
lbl3 = tk.Label(text = " ")
lbl3.place(x = 40, y = 80)

tk.mainloop()

素因数分解.png

素因数分解_入力.png

素因数分解_例.png

作りたいもの

  • タブ
  • 質問文
  • 数字を打ち込めるボックス
  • 「調べる」と書かれた、押したら下に解を表示させるボタン
  • ボタンを押したら計算して、解を求める関数

作りたいものに対応するコード

タブ

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")
``
``
tk.mainloop()

質問文

lbl1 = tk.Label(text = "調べたい数字は何ですか?").place(x = 20, y = 20)

数字を打ち込めるボックス

EditBox = tk.Entry(width=6)
``
``
EditBox.place(x = 230, y = 20)

「調べる」と書かれた、押したら下に解を表示させるボタン

btn = tk.Button(text = "調べる", command = dispLabel).place(x = 60, y = 50)

ボタンを押したら計算して、解を求める関数

def dispLabel():
    number= []
    a = int(EditBox.get())
    str_a = str(a)
    lbl2.configure(text = str_a + "=")

    while a!=1:
        for waruyatsu in range(2,a+1):
            if a%waruyatsu == 0:
                number.append(waruyatsu)
                number.append("×")
                a=int(a/waruyatsu)
                break

    number.pop(-1)
    lbl3.configure(text = number)

感想

  • 割り切れた数字の商を再び割るためにはどうすればいいか、を考えるのに時間がかかった。
  • 解を表示するときに素数の間にXをいれようとすると、どうしても一番右にも表示されてしまっていたので、どうやったら一個減らせるかを考えるのに悩んだ。
1
1
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
1
1