zoukankan      html  css  js  c++  java
  • 每日一程-14.python-打印冰雹序列

    Author: Notus(hehe_xiao@qq.com)
    Create: 2019-02-21
    Update: 2019-02-21

    给定一个正整数,打印出对应的冰雹序列

    冰雹序列

    冰雹序列是由Collatz猜想提出的。

    给出下列公式和初始的正整数值,生成的序列以1结束。

    公式如下:

    * 如果数字是偶数,除以2
    * 如果数字是奇数,乘以3,再加上1
    * 当数等于1时,退出程序
    

    从初始数字开始应用公式,然后在生成的每个数字上反复应用公式,得到整个序列。

    环境

    Python version: 3.7.1

    代码如下(a.py)

    '''
    	给定一个正整数,打印出冰雹序列。
    	@Author: Notus(hehe_xiao@qq.com)
    	@Create: 2019-02-21
    	@Update: 2019-02-21
    	@Version: 0.1
    '''
    
    theNum = input("请输入一个正整数:")
    
    while not theNum.isdigit() or int(theNum) <= 0:
    	print("请输入一个合法的正整数!")
    	theNum = input("请输入一个正整数:")
    	
    theNum = int(theNum)
    print(theNum)
    count = 1
    while theNum > 1:
    	if theNum % 2 == 0:
    		theNum //= 2
    	else:
    		theNum = theNum * 3 + 1
    	print(theNum)
    	count += 1
    else:
    	print("此序列长为: {}".format(count))
    

    运行

    C:UsersNotusDesktop>python a.py
    请输入一个正整数:10
    10
    5
    16
    8
    4
    2
    1
    此序列长为: 7
    
  • 相关阅读:
    Find the Longest Word in a String
    Check for Palindromes
    Factorialize a Number
    Reverse a String
    Java中的线程概念
    websocket 实现实时消息推送
    linux安装tomcat, jdk出现的问题
    JSON, list, 前台显示
    数据库NULL和 ‘’ 区别
    js获取后台json数据显示在jsp页面元素
  • 原文地址:https://www.cnblogs.com/leo1875/p/10415727.html
Copyright © 2011-2022 走看看