gpt4 book ai didi

c - 为什么一维奇偶校验的大O运行时是log(n)?

转载 作者:太空狗 更新时间:2023-10-29 15:26:14 24 4
gpt4 key购买 nike

所以我正在阅读这个网站的一些代码:http://www.geeksforgeeks.org/write-a-c-program-to-find-the-parity-of-an-unsigned-integer/

它展示了如何判断一个数是偶数还是奇数。但是,我不明白为什么运行时效率是log(n)。以下是引用代码:

# include <stdio.h>
# define bool int

/* Function to get parity of number n. It returns 1
if n has odd parity, and returns 0 if n has even
parity */
bool getParity(unsigned int n)
{
bool parity = 0;
while (n)
{
parity = !parity;
n = n & (n - 1);
}
return parity;
}

最佳答案

运行时效率为 O(log(n)),其中 n 是您传入的整数的。但是,这是一种非常规的 O(log(n)) 使用方式符号。

更常见的是,O 表示法根据输入的大小 以位表示(表示输入所需的位数),在这种情况下,输入的大小为 k= O(log2(n)),运行时间为 O(k)。

(更准确地说,运行时间是 Θ(s),其中 s 是 n 中设置的位数,尽管假设位操作是 O(1))。

关于c - 为什么一维奇偶校验的大O运行时是log(n)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30952512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com