一、 圓周率計算——蒙塔卡羅方法
import time
import random
DARES = 1000*1000
hits = 0.0
start = time.perf_counter()
for i in range(1, DARES+1):
x, y = random.random(),random.random()
dist = pow(x**2+y**2, 0.5)
if dist <= 1.0:
hits += 1
pi = 4 * (hits/DARES)
print("圓周率是:{}".format(pi))
print(("運行時間是:{:.5f}s".format(time.perf_counter()-start)))
二、四位玫瑰數
描述:
四位玫瑰數是4位數的自冪數。自冪數是指一個 n 位數,它的每個位上的數字的 n 次冪之和等於它本身。
例如:當n爲3時,有1^3 + 5^3 + 3^3 = 153,153即是n爲3時的一個自冪數,3位數的自冪數被稱爲水仙花數。
請輸出所有4位數的四位玫瑰數,按照從小到大順序,每個數字一行。
for i in range(1000, 10000):
a = i//1000
b = i//100 % 10
c = i//10 % 10
d = i % 10
if pow(a, 4)+pow(b, 4)+pow(c, 4)+pow(d, 4) == i:
print(i)
輸出:
1634
8208
9474
三、計算100內素數和
a = 0
for i in range(2, 100+1):
b = int(pow(i, 0.5)) + 1
for j in range(2, b):
if i % j == 0 :
break
else:
a += i
print(a)