num = int(raw_input())
def get_numbers(N):
sum1 = []
sum2 = []
i = 2
while i < N:
# we add the elements of case 2
sum1.extend(sum2)
# we add the element of case 1
sum1.append(i+1)
sum2 = [2*x for x in sum1 if x > i]
# we check for the elements with one more number when written in binary
i *= 2
# sum1 now contains all elements with two '1' in binary between 0 and the power of 2 above N.
# we remove the elements above N
sum1 = [x for x in sum1 if x <= N]
# we sort the list
sum1.sort()
# we take the length of the list, of the number of elements with two '1' in binary between 0 and N
return sum1
print(get_numbers(num))
def two_bit_numbers(N):
bit0 = 0
bit1 = 1
while True:
n = (1<<bit1) + (1<<bit0)
if n > N:
break
yield n
bit0 += 1
if bit0 == bit1:
bit1 += 1
bit0 = 0
N = 100
sum1 = 0
for i in two_bit_numbers(N):
# print i, bin(i)
sum1 += i
print sum1
如果我们看一下如何找到用二进制写时有两个“1”的数,我们得到两种情况:
因此,要查找与此情况匹配的元素数,可以执行以下操作:
这应该更快,因为我们不会测试0和N之间的每个数字,并且具有log2(N)复杂性。你知道吗
如果你对我的方法有任何疑问,请不要犹豫。你知道吗
此方法比另一个答案中的方法慢(大约慢2倍)
请尝试以下代码:
相关问题 更多 >
编程相关推荐