COMP9021 Principles of Programming Lab2

常规题目解法如下,选做题有空再补。

1. Number of trailing 0s in a factorial

任意一个数的阶乘末尾有多少个0.

from math import factorial

try:
    n = int(input('Input a nonnegative integer: '))
    if n < 5:
        raise ValueError
except ValueError:
    print('Incorrect input, giving up.')

n_factorial = factorial(n)

def divide_by_10(n):
    count_0 = 0
    while(n % 10 == 0):
        count_0 += 1
        n //= 10
    return count_0

def string_0(n):
    count_0 = 0
    n = str(n)
    while(n[-1] == '0'):
        count_0 += 1
        n = n[:-1]
    return count_0

def nb_of_5(n):
#计算一个整数中有多少个质因子5
    nb = 0
    while (n % 5 == 0):
        nb += 1
        n //= 5
    return nb

def smart_5(n):
#转化问题,n!末尾有多少个0 = n!能被多少个10(2*5)整除;
#对阶乘而言,被2整除可能性高于被5整除,例如,只要阶乘中有一个偶数就可以被2整除,但是被5整除,阶乘必须大于5
#n!能被多少个10(2*5)整除 = n!有多少个质因数5
#n!有多少个质因数5 = n, n-1, n-2, ... 5中共有多少个质因数5
#n, n-1, n-2, ... 5中共有多少个质因数5 = 被5^1整除的数的个数 + 被5^2整除的数的个数 + ...
#例如26!,能被5整除的数有5, 10, 15, 20, 25。被5^1整除的数共5个,然后计算被5^2整除的数的个数共2个,所以总共贡献了7个质因数5。
    count_0 = 0
    for e in range(1, n+1):
        count_0 += nb_of_5(e)
    return count_0

print(f'Computing the number of trailing 0s in {n}! by dividing by 10 for long enough: ', divide_by_10(n_factorial))
print(f'Computing the number of trailing 0s in {n}! by converting it into a string: ', string_0(n_factorial))
print(f'Computing the number of trailing 0s in {n}! the smart way: ', smart_5(n))

2. Perfect numbers

A number is perfect if it is equal to the sum of its divisors, itself excluded. For instance, the divisors of 28 distinct from 28 are 1, 2, 4, 7 and 14, and 1+2+4+7+14 = 28, hence 28 is perfect. Write a program perfect.py that prompts the user for an integer N. If the input is incorrect then the program outputs an error message and exits. Otherwise the program outputs all perfect numbers at most equal to N. Implement a naive solution, of quadratic complexity, so that can deal with small values of N only.

import sys

try:
    n = int(input('Input an integer: '))
    if n <= 1:
        raise ValueError
except ValueError:
    print('The input is not legal.')
    sys.exit()

def perfect(n):
    divisor = []
    for i in range(1, n):
        if (n % i == 0):
            divisor.append(i)
    total = 0
    for e in divisor:
        total += e
    if total == n:
        return True
    else:
        return False

for i in range(1, n+1):
#range范围要注意,1不是perfect number,最后要用n+1才能包括n
    if perfect(i):
        print(f'{i} is a perfect number.')

3. Decoding a multiplication

#三位数×两位数,结果4位数,中间过程两个数一个4位一个3位,每列数字和一样
#   4  1  1
#*     1  3
#----------
#1  2  3  3
#4  1  1
#----------
#5  3  4  3
#sum column
#10 10 10 10
'''
def column_equal(multiple_1, multiple_2, middle_1, middle_2, result):
    column_1 = multiple_1%10 + multiple_2%10 + middle_1%10 + result%10
    column_2 = multiple_1//10%10 + multiple_2//10 + middle_1//10%10 + middle_2%10 + result//10%10
    column_3 = multiple_1//100 + middle_1//100%10 + middle_2//10%10 + result//100%10
    column_4 = middle_1//1000 + middle_2//100%10 + result//1000%10
    column_5 = middle_2//1000 + result//100000
    if column_1 == column_2 and column_2 == column_3 and column_3 == column_4:
        if column_5 == 0:
            return (True, column_1)
        elif column_4 == column_5:
            return (True, column_1)
        else:
            return (False, column_1)
    else:
        return (False, column_1)

for i in range(100, 1000):
    for j in range(10, 100):
        middle_1 = i * (j % 10)
        middle_2 = i * (j // 10)
        result = i * j
        col = column_equal(i, j, middle_1, middle_2,result)
        if col[0]:
            print(f'{i} * {j} = {result}, all columns adding up to {col[1]}.')

4.Estimating the probabilities of hypotheses in the light of more and more evidence

Write a program bayes.py that simulates the cast of an unknown die, chosen from a set of 5 dice with 4, 6, 8, 12, and 20 faces. To start with, every die has a probability of 0.2 to be the chosen die. At every cast, the probability of each die being the chosen die is updated using Bayes’ rule (find out about it if you do not know it). The probabilities are displayed for at most 5 casts. If more than 5 casts have been requested, the final probabilities obtained for the chosen number of casts are eventually displayed.

To be continued

你可能感兴趣的:(COMP9021 Principles of Programming Lab2)