PTA: Python implementation (3n+1) conjecture

Please scroll to the end of the article for the source code of the topic!

Table of contents

topic:

Input format:

output format

Input sample:

 Sample output:

Detailed source code:

Execute input code

 Execution condition condition:

full source code

Explanation of knowledge points:

Knowledge points used in this question:

(1) Mandatory type conversion

(2) input() input

(3) while loop

(4) if judgment

(5) print() output


topic:

        Callatz conjectures:

        For any positive integer n, if it is even, then cut it in half ; if it is odd, then cut (3n+1) in half . This has been cut down repeatedly, and finally n=1 must be obtained at a certain step . Karaz announced this conjecture at the World Congress of Mathematicians in 1950. It is said that the teachers and students of Yale University mobilized to prove this seemingly silly and naive proposition. +1), so that some people say that this is a conspiracy, that Karaz is deliberately slowing down the progress of teaching and scientific research in the American mathematics community...

        Our topic today is not to prove the Karaz conjecture, but for any given positive integer n not exceeding 1000, simply count, how many steps (cuts) are needed to get n=1 ?


Input format:

Each test input contains 1 test case, i.e. given the value of a positive integer n.

Output format:

Output the number of steps needed to compute from n to 1.

Input sample:

3

Sample output:

5

Detailed source code:

Execute input code

n = int(input())

Execution condition condition:

If it's even then cut it in half

if n % 2 == 0:
    n = n / 2

If it's odd, then chop (3n+1) in half

elif n % 2 == 1:
    n = (3 * n + 1) / 2

        In the end, n=1 must be obtained at a certain step, because the program is a loop, and the condition to end the loop is n=1, then the execution condition is to execute when n>1, so I use a while loop here to add the execution condition.

while n > 1:

        The final step is to count the number of cycles. Here we can define an i=0, so that every time the loop is executed, i+=1 is executed, which is equivalent to i=i+1, and finally i is directly output.


full source code

n = int(input())
i = 0
# n=1时退出循环,程序结束
while n > 1:
    # 判断n是否为偶数
    if n % 2 == 0:
        n = n / 2
    # 判断n是否为奇数
    elif n % 2 == 1:
        n = (3 * n + 1) / 2
    # 每循环一次就+1,直到循环结束
    i += 1
print(i)

Explanation of knowledge points:

Knowledge points used in this question:

(1) Mandatory type conversion

int(), fill in the data that needs to be converted in the brackets

(2) input() input

(3) while loop

(4) if judgment

if judgment, add execution conditions after if, and execute an operation if the conditions are met

(5) print() output

Guess you like

Origin blog.csdn.net/weixin_62854251/article/details/130546235