This is the correct answer.
Hardcode a list of the first 40 Fibonacci numbers, and iterate through the body of text, counting "n" as you go. When n= {fibonacci num on list} print word read next highest fibonacci num iterate some more.
"Infinite Jest" has 578,000 words. The 30th Fibonacci number is 832,040, so hardcoding the first 30 numbers will get you through most novels.
hardcoding the first 40 will get you through a word list of 102 million. This is more than double the size of the Encyclopedia Britannica's 40 million words.
I doubt that hardcoding is the way to go. To calculate the next fibonacci is a single add of cpu registers. Looking things up in a table seems like it would actually take longer.
Incorrect.
You'vr omitted all the steps necessary to get the next Fibonacci number loaded into a register. (ironically, this is what hardcoding accomplishes, btw)
Your way: A math operation is require loading value 1, mathop to calculate next fibonacco value, saving value 2, compare operation to index number.
My way: A hardcoded table gets turned into a memory resident space by the compiler, never gets swapped, and requires only a lookup, and a compare. Pointer just moves one byte to next stored number, then a compare of the two registers.
It's not just a little faster; it's probably 4x faster.
Admittedly,I'm a little rusty on the inner workings of the cpu, but the table would be in a cache and not in registers, correct? So the lookup operation you refer to means it would have to be fetched from the cache into a register before the compare which AFAIK is slower vs a simple add and store of the previous 2 Fibonacci numbers happening all within registers.
https://www.gktoday.in/topic/which-is-the-fastest-computer-memory-register-or-cache-3/
(post is archived)