请举一个简单的计数示例

时间:2017-05-30 18:21:59

标签: javascript algorithm

在Javascript和Python中,每天加倍一美分将花费多少天?

var count = 0
for (var i=0; i<10000; i++) {
    count += 1
}

以上代码是我要找的回复。我是初学者,发现知道简单的解决方案有时可以帮助解决更大的问题。

4 个答案:

答案 0 :(得分:1)

这是Python中的问题解决方案。

pennies = 1
days = 0 
while (pennies < 10000*100) : 
    pennies *= 2
    days += 1
print ( days , 'days to reach 10000')

答案 1 :(得分:1)

var pennies_total = 1 // total amount of pennies
var days_total = 1    // days past
var pennies = 1       // doubled amount for the current day

while (pennies_total < 10000*100) {
    pennies *= 2              // doubling pennies for current day
    pennies_total += pennies  // adding the doubled pennies to the total
    days_total += 1           // increasing the days count
}

print days_total

答案 2 :(得分:0)

我不明白这是否是一个问题,因为你说“上面的代码是我正在寻找的回应”。因为代码没有回答这个问题“在Javascript和Python中,每天加倍一分钱将花费多少天?”我认为是的。

pennies = 1
days = 0

while ((pennies / 100) < 10000):

    pennies *= 2
    days += 1

答案 3 :(得分:0)

如果您在询问如何找到将值加倍到10,000倍所需的次数,那么您希望更改循环条件以及循环中的操作。

var count = 1; // Start at 1 because we "have 1 penny" already
var i; // Define an index in this scope to keep track of times doubled
for (i=0; count < 10000; i++) { // Check that the penny count is less than 10,000... not the number of iterations
    count *= 2; // Multiply the current value of count by 2
}
console.log(i); // Print # times that the penny was doubled
console.log(count); // Print the value of count (it might not be 10,000 exactly)

如果您想要更高效和准确的解决方案,您可以始终执行基数2对数:

Math.log2(10000); // 13.287712376549449

要获得一个整数,只需Math.ceil()它(因为从技术上讲,如果你过去 - 即使是很小的数量 - 你需要再加倍才能达到该值)。

Math.ceil(Math.log2(10000)); // 14

最后,如果您只是在寻找这个数字:至少需要10,000天便可用14天