1.打印前十个质数
Print first 10 primer numbers
# print first 10 primer numbers
j=0 # 对素数数的计数
for num in range(2, 100):
for i in range(2, num):
if num % i == 0:
break
else: # 如果没执行break,就会到执行else
if j < 10:
print(num)
j += 1
2.找到两个数的最大公约数:
Given two positive integer numbers, calculate the greatest common divisor of them.
我的方法:遍历来找,时间复杂度太高了
# Given two positive integer numbers, calculate the greatest common divisor of them.
a = int(input("please enter an integer number:"))
b = int(input("please enter another integer number:"))
if a > b:
a,b = b,a
for i in range(1, a):
if a % i == 0 and b % i == 0:
k = i
print("\n")
print("the GCD is {}".format(k))
欧几里得的方法:
不断取余数,再取余数与较小数的余数。当为0时,即为最大公约数。时间复杂度小。
设较小数为N,较大数为M,最大公约数为g:
int n,k,m
N = ng, M = (kn+m)g
取余后可以得到mg,再用mg和ng进行比较,最后整除的时候得到g
# greatest common divisior
a = int(input())
b = int(input())
if a > b:
a, b = b, a
while a != 0:
a, b = b % a ,a
print( b )
3.Given a positive integer number n, Calculate a + aa + aaa + aaaa
- aaa…aaaa + ……(there are n items)
a is a positive integer number, such as a = 2, n = 4
then the result is 2 + 22 + 222 + 2222 = 2468
# Given a positive integer number n, Calculate a + aa + aaa + aaaa + aaaaa...(there are n items)
a = int(input("please enter an integer:"))
n = int(input("please enter the items number:"))
sum = 0
for i in range(0, n):
k = a * (10 **i)
sum = sum + k
print("\n")
print("the result is {}".format(sum))
4.自幂数
A narcissistic number is a number that is the sum of its own digits each raised to the power of the number of digits.
such as 2, 72, 90, 108, 153, 270, 423…
for 153, because 111 + 555 + 333 = 153, 153 is a narcissistic number
Write a program, print all of the narcissistic number ranging from 0 to 10000.
刚学的时候我的方法(十分愚蠢,把代码分成了好多个部分):
# Write a program, print all of the narcissistic number ranging from 0 to 10000
for a in range (0, 10):
if a == a:
print(a,end=' ')
for qw in range(11, 100):
q = qw // 10
w = qw % 10
if qw == q ** 2 + w ** 2:
print(qw,end=' ')
for sdf in range(111,1000):
s = sdf // 10 // 10
d = sdf // 10 % 10
f = sdf % 10
if sdf == ((s ** 3) + (d ** 3) + (f ** 3)):
print(sdf,end=' ')
for ghjk in range(1111, 10000):
g = ghjk // 10 // 10 // 10
h = ghjk //10 // 10 % 10
j = ghjk //10 % 10
k = ghjk % 10
if ghjk == g ** 4 + h ** 4 + j ** 4 + k ** 4:
print(ghjk,end=' ')
现在我的方法:
for i in range (10001):
sum = 0
b = str(i)
count = len(b)
for j in range(count):
a = b[j]
sum += pow(int(a), count)
if sum == i:
print(i, end = ' ')
5.Print the following pattern
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
for x in range(1, 6):
for y in range(1, x+1):
print(y, end=' ')
print("")
6.Print the following pattern using for loop
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
在这里插入代码片for x in range(1, 6):
for y in range(1, 7 - x):
y = 7 - x - y
print(y, end=' ')
print("")