We spend a lot of time trying to write good code. I don't know about you, but I get weary of hearing the (apt) admonishment "don't be clever".
Everyone needs a break. So, in celebration of all our diverse skills and knowledge, Let's Get Clever!
Challenge #1
Calculate the Nth digit of the Fibonacci sequence.
In the Fibonacci sequence, every element is the sum of the previous two terms.
0, 1, 1, 2, 3, 5, 8...
So, the next value is 5 + 8
, or 13
.
Your code should be able to find the n
th element.
Constraints
No hard coding allowed! You may not write out the sequence manually anywhere in your code. Every element (except the initial
0, 1, 1
) must be generated by the code.n=0
is0
;n=1
andn=2
are both1
Assume
0 <= n < (2^16 â 1)
. In other words, don't worry about negative numbers, and assumen
is less than the maximum possible value of a 8-bit integer. (Yes, it USED to be a 64-bit integer...I updated the spec to be sane.)
Bonus Points
These are NOT required, but if you achieve any of these goals, major bragging rights!
ð No Loops: Can you avoid use of any explicit loops or recursion?
â±ïž Efficiency: Can you beat
O(n)
?
The Rules
(These will be the same for every Let's Be Clever challenge.)
Your clever code should accomplish the stated goal in whatever way you like. Watch out for edge cases, though.
You may use any language you like. However, I discourage use of deliberately esoteric languages. Cleverness is usually more fun in production languages.
You know all those rules about readability and maintainability? Fuhgeddaboudit. Cleverness is the goal.
Portability, memory safety, security? Bah humbug. Mel is welcome.
Efficiency is not the main goal, but if your cleverness happens to have an efficiency worth bragging about, definitely point it out!
Explain your Cleverness. Don't wait for others to ask you, although you should be prepared to answer questions. The neat side-effect of Clever code is that everyone can learn cool, weird things.
Be open to feedback. Others might be able to spot edge-cases you missed, or have ideas on how to make your Clever approach even more clever.
Preening is permitted, but don't be obnoxious about it, and be equally liberal with your complements of others. Leave false modesty in the drawer. (Imposter Syndrome sucks, so let's use this to give it a good kick in the teeth.)
Upvote Cleverness! If you really like someone's solution, be sure to give it a Like.
Always be polite and constructive. Please don't criticize anyone for not being clever enough, not understanding what you did, or asking a "stupid question". This is Cleverness on display. Be the tour guide!
Don't forget: CODE HACKERY ENCOURAGED! No holds barred.
Top comments (52)
How is it , took help geek from geeks ,though
Don't forget to wrap your code in triple backquotes (`) above and below! That sets it out from the rest of your post, like I have in my comment. You can also force syntax highlighting by naming the language after the first three backticks.
thank you ,sir for guiding.Actually I am new to this forum
Ah, then welcome!
Take a look at our Editor Guide for more about the neat things you can do in posts and comments.
Also, be sure to drop in on the Welcome Thread
was my code alright ?
Ah yeah, mate. Sweet and simple!
wew, though I have left this type programming and switched onto web dev , but still like to solve these odd problems.
Well, how would you solve it with web dev technologies? (repl.it is awesome if you need a sandbox for any language). I bet you'd have some clever solution with, say, Javascript!
sir it's like that, i have studied these logics in my programming courses at my university.So just got the idea from there.As for sandboxes I am up for it anyday.Plus, I am a begginer at JS still revising my basics and getting onto the advanced version and then onto the Angular framework
Waaaaaaaaaait....I just took a closer look at your code.
It works great.
...and....HOW? I mean, it's staring me in the face, I can feel how it's working. I can even see it. But it just...doesn't look like it should?
Woah.
(Definitely edit and wrap it in backticks [and fix the
#include
]. It deserves to be displayed in all its brilliance.)done :)
Oh...close, but, yeah, not quite. Try this.
thank you for the guidance.
Python solution that uses the fact that the ratio of consecutive numbers in the sequence approaches Phi
This is closely related to my closed form solution, as they are both based on Binet's Formula
Using a hard-coded value, mine can be reduced as well:
Where
Ï
is the Phi value you are using.Wow, so we can actually get O(1) with this? Amazing
It s not actually O(1) since ** n takes time too :))
I tried running the code but when I tried to run fib(10) it returns
1
, did i do something wrong?Nope, I made a stupid mistake when writing this function on Dev.to, I originally wrote it in the REPL. Fixing it now.
Excellent stuff!
This one is absolutely beautiful.
In Perl 6 you can do something like this:
This make uses of the ... sequence operator, which will produce (possibly lazy) generic sequences on demand.
Then you can get the first
10
Fibonacci numbers:More detailed explanation about this (not mine) could be found at: perl6.online/2018/12/15/playing-wi... and perl6advent.wordpress.com/2010/12/...
If you could get this to return a single number for value
n
, you'd be set up to get the bonus points for no loops or recursion! ðRuby hashes (a.k.a dictionaries) accept a block to calculate missing entries.
You can abuse this mechanism and store only 0 and 1, and then use the
default_proc
for everything else:Here is the DP solution in javascript.
O(n) runtime complexity
O(1) space complexity
some loss in the fidelity of the computation since computations used to build upto fib(n) are lost.
maintaining fidelity would probably be better in practical use since saving the pre-computed values would lead to O(1) complexity for values already computed.
In compiled languages you could do this step in compile time and then cache them for O(1) runtime, but you would sacrifice some space O(n) space complexity
for some reason I started on a mission to calculate fib of 1 million, so I edited the above code to include an execution time, and use big ints from javascript this let me calculate fib(1,000,000) in 88s
+1 for one-upping yourself, mate! ;)
I wonder how long
n=(2^63)â1
would take. It may not even be achievable. My own code won't even manage it....I should tweak the spec to limit it to
(2^16)-1
;)given 1e6 is 88s, and 2e63/1e6 = 9.223e12, I would guess 8.116e14 seconds or 25,737,466.3636 years
So, not long at all. ;)
though JavaScript's Big Int library should allow for a number as big as your memory can hold. I think 4GB = 16gb = 16e+9 bits or digits, so theoretically if I could get absolute precision working with the closed form solution mentioned by edAâqa mortâoraây. Then the largest theoretical number I can handle would be 9.99999...e+16,000,000,000.
I'm going for the bonus points, no explicit loops nor recursion, and O(1) time*.
This is a closed form evaluation of the n-th fibonnaci number.
The
int
cast is because thedouble
isn't precise enough, thus a bit of error value accumulates. Remove it to see how much.** Time complexity, you might get picky here and we can debate what the time complexity of
**n
is. In worst case it shouldn't be more thanlog(n)
given that the genericpow
islog(n)
.HA! I was getting worried that the efficiency bonus goal was actually impossible, but I just had that nagging feeling there was some algorithmic way of solving this without generating each preceding element.
Everything is more fun with unicode:
Interesting in javascript this will have precision errors after fib(75).
Probably because of the limitations on floating point math precision.
Golly that was hard to do on mobile!
No need for maths or recursion here, let's use base 0 with a loop!
Which language is this? I suspect Java, but I'm not sure at a glance.
This reminds me a bit of my alternating pair approach (in C), but it's strangely lovely. Nice work.
P.S. Did you mean for
y += X
to have an upper caseX
?Thank you! It's JavaScript, easiest thing for me on my phone. And I did not, thank you! I'll change it now.
I figure it could probably be made much fancier, but I'm not up for it right now!
Shoot, bonus points for typing it on mobile at all, mate. ;-)
I couldn't resist one more pass, using C.
I'm using a pair to calculate the sequence, ergo the 2-element integer array.
Before I can do anything, though, I need to know where my answer will show up, so I create a pointer to the element which will eventually hold the result. That way, I can mutate
n
without fear. How this works will become apparent in a second.This next line has a label,
g
, which I'll be using in a moment. In this math, I'm alternating which of the two elements in the pair are used to store the sum, and I'm switching between them by checking ifn
is even or odd (n%2
), yielding either1
(odd) or0
(even). In the middle of that, I'm also decrementingn
after I've used its value. I take the sum of the two elements, and save it in the target position in the pair. This way, I always have the latest two elements.On the next line, if
n
has a non-zero value, I jump back to that previous line, using itsg
label. I'm using agoto
statement, instead of an explicit loop or recursion (so, technically I hit one of the bonus goals? Debatable.)Once I'm done, and
n
has reached zero, I return whatever was in the position I originally stored to look for the answer in. Remember how I was using the modulo to alternate spots? That same logic is at work here. If the originaln
was even, then the last value will get written to the first spot in the pair; if the originaln
is odd, then the second spot will be used.Nice compact answer, goto still counts as a loop though ;)
Lisp version (using emacs)
Using Kotlin:
Generate a
Sequence
(infinite stream of data) starting with 1, 1. Each next element is the second number of the pair + their sum. UseelementAt
to get the n-th pair. The result is the first number of the pair.Try it out online: pl.kotl.in/MOeDSCD4v