亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

快樂數程序使用數組,幫我計算時間復雜度?

快樂數程序使用數組,幫我計算時間復雜度?

小怪獸愛吃肉 2023-05-16 15:53:32
我用數組寫了一個Happy number程序,請問如何計算時間復雜度?如果在用等于其所有數字的平方和的數字反復替換它之后,將我們引向數字“1”,則任何數字都將被稱為快樂數字。所有其他(不快樂的)數字永遠不會達到“1”。相反,他們將陷入不包括“1”的數字循環中。def happy(num):    ls = []    result = 0    while True:        result = sqr_digits(num)        if result == 1:            return True        elif result in ls:            return False  # not happy        else:            ls.append(result)            num = resultdef sqr_digits(num):    result = 0    while(num > 0):        digit = num % 10        result += digit ** 2        num //= 10    return result    num = 145    print(happy(num))
查看完整描述

1 回答

?
慕森王

TA貢獻1777條經驗 獲得超3個贊

[注意:在回答問題時,我忘記了你的代碼正在使用digit^2,但我只是提供了基于digit. 復雜度計算機制相同。digit^2如果您閱讀答案,您可以輕松地自己找出復雜性。當我有時間時,我會更新答案。希望你不會介意]


好吧,如果有一個 number n(base 10),那么它最多可以有log10(n) + 1數字。我希望,我不會解釋它......只是谷歌它how many digits in a 10 based number and how to find it using log。


現在,讓我們解釋一下所提供算法的復雜性:


只有當總和變為個位數時,算法才會停止。


所以,我們可以計算位數,我們必須添加,這將是最終的復雜性。


精確計算該算法的復雜性是不可能的,但我們可以計算最壞情況的復雜性……最大數當然是3 digits,999所以我們總是考慮d nines一個d digits數字。


1st iteration:: no of digits, d1 = log10(n) + 1, and n1 = d1*10, (originally d1*9 in worst

case, but we're taking much worse and the reason is to calculate complexity properly)



2nd iteration:: no of digits, d2 = log10(n1) + 1 and n2 = d2*10

                                 = log10(d1*10) + 1

                                 = log10(d1) + 1 + 1 (cause, log(a*b) = log(a)+log(b))

                                 = log10(log10(n) + 1) + 1 + 1



3rd iteration:: no of digits, d3 = log10(log10(log10(n)+1)+1) + 1 + 1 + 1


...

...

我想,你可以看到這是怎么回事??偽粩悼梢詫憺椋?/p>


total digits = d1 + d2 + d3 + ....


By removing the 1 inside log's(for simplification) we can write simply:

total digits = log10(n) + 1 + log10(log10(n)) + 2 + log10(log10(log10(n))) + 3 + ...


but, log10(n) + 1 >>> log10(log10(n)) + 2

所以,我們可以看到最終的復雜度是由 決定的log10(n)。最終的復雜性將是:


complexity = c * log10(n) // here is "c" a constant such that c * log10(n) > total digits

which

we can say O(log10(n))

我希望你已經正確理解了這個概念......


查看完整回答
反對 回復 2023-05-16
  • 1 回答
  • 0 關注
  • 133 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號