基礎(chǔ)代碼題

#最大公約數(shù)
def gcd(a, b):
    while b:
        a, b = b, a%b 
    return a 

a = 21
b = 9
print(gcd(a, b))  # 最大公約數(shù)
print(a*b/gcd(a,b))  # 最小公倍數(shù)



# 多個(gè)數(shù)的gcd
def arr_gcd(A):
    gcd = A[0]
    for a in A:
        while a:
            gcd, a = a, gcd % a
    return gcd 

print(arr_gcd([3, 6, 21]))
# 素?cái)?shù)篩選
import math

maxInteger = 1000000
prime = [True]*maxInteger
prime[0] = False
prime[1] = False

for i in range(2, (int)(math.sqrt(maxInteger)+1)):
    if prime[i]:
        for j in range(i*i, maxInteger, i):
            prime[j] = False
print(prime[11])
# 合并有序鏈表
import numpy as np 

class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next

a = ListNode(1, ListNode(2, ListNode(3)))

b = ListNode(1, ListNode(4, ListNode(5)))

def sort_listnode(a, b):
    result = ListNode(0)
    cur = result
    if a is None:
        return b
    if b is None:
        return a 
    while a and b:
        if a.val < b.val:
            result.next = a
            a = a.next
        else:
            result.next = b
            b = b.next
        result = result.next
    if a is None:
        result.next = b
    if b is None:
        result.next = a 
    return cur.next
 
result = sort_listnode(a, b)

while result:
    print(result.val)
    result = result.next
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容