알고리즘/codefights
Challenge>fibonacciIndex
Diademata
2019. 3. 6. 00:58
반응형
Consider the Fibonacci sequence: 0 1 1 2 3 5 8 13 21 ... We can see that 7 is the smallest 0-based index k for which F(k) has exactly 2 decimal digits. What is the smallest index k for which F(k) has exactly n decimal digits? Example For n = 1, the output should be fibonacciIndex(n) = 0; For n = 2, the output should be fibonacciIndex(n) = 7. |
code>>
int fibonacciIndex(int n) {
if (n == 1) return 0;
int f = 0, s = 1, t = 1, idx = 1;
while (std::to_string(t).size() != n)
{
t = f + s;
f = s;
s = t;
idx++;
}
return idx;
}
반응형