r/dailyprogrammer • u/jnazario 2 0 • Oct 14 '15
[2015-10-14] Challenge #236 [Intermediate] Fibonacci-ish Sequence
Description
The Fibonacci Sequence is a famous integer series in the field of mathematics. The sequence is recursively defined for n > 1 by the formula f(n) = f(n-1) + f(n-2). In plain english, each term in the sequence is found by adding the previous two terms together. Given the starting values of f(0) = 0 and f(1) = 1 the first ten terms of the sequence are:
0 1 1 2 3 5 8 13 21 34
We will notice however that some numbers are left out of the sequence and don't get any of the fame, 9 is an example. However, if we were to start the sequence with a different value for f(1) we will generate a new sequence of numbers. Here is the series for f(1) = 3:
0 3 3 6 9 15 24 39 102 165
We now have a sequence that contains the number 9. What joy!
Today you will write a program that will find the lowest positive integer for f(1) that will generate a Fibonacci-ish sequence containing the desired integer (let's call it x).
Input description
Your input will be a single positive integer x.
Sample Input 1: 21
Sample Input 2: 84
Output description
The sequence of integers generated using the recursion relation starting from 0 and ending at the desired integer x with the lowest value of f(1).
Sample Output 1: 0 1 1 2 3 5 8 13 21
Sample Output 2: 0 4 4 8 12 20 32 52 84
Challenge Inputs
Input 1: 0
Input 2: 578
Input 3: 123456789
Notes/Hints
Large inputs (such as input 3) may take some time given your implementation. However, there is a relationship between sequences generated using f(1) > 1 and the classic sequence that can be exploited.
Bonus
Make your program run as fast as possible.
Credit
This challenge was suggsted by /u/nmacholl. Have a good challenge idea? Consider submitting it to /r/dailyprogrammer_ideas and we might use it
25
u/Blackshell 2 0 Oct 14 '15 edited Oct 14 '15
It turns out that what the Fibonacci-ish sequences contain just multiples of the regular Fibonacci sequence. The factor is the value of f(1). To find the lowest possible value of f(1), you have to iterate over the regular Fibonacci sequence to find the highest member of it that is a factor of the given integer
x. Divide x by that number and you have your value of f(1).Code hosted at: https://github.com/fsufitch/dailyprogrammer/blob/master/236_intermediate/solution.py
Input results and processing time:
x = 0 (how does this one even make sense?)
x = 578
x = 123456789
x = 38695577906193299 (for a real challenge)
10
u/cym13 Oct 14 '15
Just to play, using Linotte (a French-based programming language dedicated to teaching programming). The code is ugly but still, enjoy:
9
u/casualfrog Oct 14 '15 edited Oct 16 '15
JavaScript (feedback welcome)
Edit: This is pretty concise, but not nearly as fast as this version
Edit2: Fastest JavaScript solution below by /u/hastyrobot
Uses the property that
Code:
Output:
6
u/wizao 1 0 Oct 14 '15 edited Oct 14 '15
I wanted to share an excellent page I found that walks through the math behind the more general fibonacci-ish sequences where both starting values can vary. The same author has another page on just the fibonacci sequence which is also very good.
6
u/wizao 1 0 Oct 14 '15 edited Oct 14 '15
Haskell:
4
u/fvandepitte 0 0 Oct 14 '15 edited Oct 15 '15
Haskell, feedback is welcome. It runs almost instant on input 3
Edit Changed input parsing to have all challenge inputs at once
Edit 2 Added /u/BlackShell 's input to the list, results are still instant
EDIT 3 Removed
idvariable, since it wasn't necessary and as /u/wizao pointed out. It is not done to overshadow the Prelude (not that I knew I was doing that)4
u/h2g2_researcher Oct 14 '15
Here's a fully portable, multithreaded C++11 solution. It will hit you in the memory a little bit.
Running in release mode I get the results:
Obviously these are quite machine dependent (Intel Xeon @2.40GHz, quad-core, 8GB of RAM) and maybe compiler dependent (Microsoft C/C++ Optimizing Compiler v 18.[something]).
4
u/G33kDude 1 1 Oct 14 '15
Done in one line of Python (plus one extra for calling it). Output for a number
nis a list of valuesvwheref(1)=vandnis a member off.+/u/CompileBot Python2.7
4
u/zengargoyle Oct 15 '15
Perl 6
It's almost Chrismas time (yay!).
Test
3
u/[deleted] Oct 14 '15 edited Oct 14 '15
Python brute force. Feedback appreciated.
EDIT: Seems to be horribly slow for
123456789, so here's the same in Java that takes 3.5s:3
u/curtmack Oct 14 '15 edited Oct 14 '15
Clojure
Laziness!
Time and output:
So I'm pretty sure I meet the Bonus criteria.
Edit: FWIW, I'm pretty sure most of that 1.733s is JVM and Clojure overhead. I'd be very surprised if the actual processing took longer than a quarter second. I'll get it properly timed at some point.
3
u/ChazR Oct 15 '15
Ok: Haskell again. This time we use a linear-time generator and runs close to instantly on any input.
2
u/demeteloaf Oct 14 '15 edited Oct 14 '15
erlang: (feedback welcome).
Pretty naive implementation, but I have to go to work and needed to do this quickly, I may get a better idea for this later.
Output:
Last one definitely does take a while.
2
u/panda_yo Oct 14 '15 edited Oct 14 '15
A quick question and/or maybe a tip:
This should do the trick in Java: import java.util.*;
The solution is:
Was pretty fast.
2
u/fvandepitte 0 0 Oct 14 '15
C++ Actually Copy of my Haskell solution. Also damn fast (need to profile it)
2
u/run-forrest-run Oct 14 '15 edited Oct 14 '15
A little late, but here's my solution in Python:
And the output:
Case 1 - f(0):
Case 2 - f(578):
Case 3 - f(123456789):
Bonus Round f(62610760266540248):
Edit: Made it slightly better at handling f(0)
2
u/NihilCredo Oct 14 '15 edited Oct 15 '15
F# script
Feedback welcome.
Running this with F# Interactive on the sample and challenge inputs, plus 987654321 gives these results. I think either I'm using #time wrong or it's really inaccurate - 4ms can't be right.
If I use dotNetFiddle instead I seem to get either ~30ms or 140-150ms, more or less at random. Those seem more sensible numbers but I can't figure out what makes it go fast or slow (the ~30ms happens with new numbers too so I don't think it's some sort of caching).
EDIT: I added a Stopwatch(), which is the "proper" .NET execution time measurement at a quick Googling. The results match those from F# Interactive: I get 3ms, sometimes 2ms, whatever input I punch in. So, I guess I get the bonus? :D
2
u/alisterr Oct 15 '15 edited Oct 15 '15
Rust This time I tried to do it before reading other people's code. It's surprisingly fast, see the output below. Suggestions are appreciated :)
Code:
Output: 578
123456789
38695577906193299
3
u/a_Happy_Tiny_Bunny Oct 14 '15 edited Oct 15 '15
Haskell
Most naïve solution:
Actually doing the maths:
This one takes several lines of input. I changed the functions to work on
Intinstead of the more generalIntegralclass in trying to optimize. I usedremfor the same reason. However, the program runs virtually instantly for these inputs.1
u/thursday42 Oct 14 '15 edited Oct 14 '15
Java. I'm sure there are better ways to do this, but it seems to work pretty well, and takes about 3-4 seconds to finish. Edit: Added missing import statement, cleaned up code.
Output:
1
u/TiZ_EX1 Oct 14 '15
Haxe
My math is pretty weak so I just brute-forced it. Feedback appreciated.
Compiling to the cpp target gives a pretty acceptable speed, though it's not as fast as /u/szerlok's Java implementation.
1
u/glenbolake 2 0 Oct 14 '15
Python 3. I had a brute force copy, then I noticed /u/casualfrog mention what the property alluded to in the Notes/Hints section was.
1
u/skeeto -9 8 Oct 14 '15
C, brute force. Solves the challenge input in 200ms.
1
u/Leo-McGarry Oct 14 '15 edited Oct 14 '15
C Sharp
Currently brute forced.
Results:
1
u/Squiddleh Oct 14 '15
Still new to Swift 2.0 (and programming in general), feel free to improve.
1
u/Minolwa Oct 14 '15
Java Solution (runs in ~6.5 seconds):
Output:
As any programmer should be, I am open to feedback.
1
u/demonicpigg Oct 14 '15
PHP solution. Accessible at http://chords-a-plenty.com/Fibonacci.php
As a side note, I'm using a formula for getting fibonacci numbers I haven't seen anyone else use.
Output:
1
u/Godspiral 3 3 Oct 14 '15
In J, without fancy math,
first a fibonaci function with flexible inputs
0 1 1 2 3 5 8
the 0 1 part is just changed for this challenge to 0 x.
17
too slow for input 3.
1
u/KeinBaum Oct 14 '15 edited Oct 14 '15
Scala
Returns pretty much instantly for the challenge inputs.
Challenge Outputs:
The math behind it.
1
u/[deleted] Oct 14 '15
Solution in C++, brute force. I haven't optimized this yet. I'm hoping to get around to it today. Any feedback is appreciated.
Output:
1
u/wholodolo Oct 14 '15 edited Oct 14 '15
Scheme
Results:
1
u/JoeOfDestiny Oct 14 '15
Brute force in Java seems to do just fine.
I realize the property that
but this doesn't seem very helpful because factoring numbers isn't necessarily computationally easier than just calculating out the sequence.
1
u/marchelzo Oct 14 '15
Here's what I came up with after reading some of the discussion here. It solves all three challenge inputs more or less instantly.
1
u/Eggbert345 Oct 14 '15 edited Oct 14 '15
Golang solution. Took advantage of the fact that a number would be a multiple of a Fibonacci number, as well as an amazing property to determine if a number is a Fibonacci number without having to generate the whole sequence. Links to references in code.
Edit: Small optimizations that brought it down to 0.008s Edit2: I was including compilation time in the run time. Stupid.
1
u/TichuMaster Oct 14 '15
My solution in JAVA. (not sure how fast it is)
Code:
}
I would love to hear any comments.
1
u/ChazR Oct 14 '15
Haskell, really naïve version. Is slow.
I can see the optimisation, and am going to think a bit about how to implement it efficiently.
1
u/AnnieBruce Oct 14 '15
I just happened to have a fibonacci implementation with an @lru_cache decorator on it, which to me seemed to be an amazing thing to use for this. Since I'd have to start from the bottom to find the scaling factor, the cache should end up with a very high hit rate, maximizing the speed boost it provides.
Also found a chance to play around with slightly more complicated list comprehensions than I've dealt with before. These may or may not be the best ways to solve those particular parts of the challenge, but I needed the practice with comprehensions.
Returns near instantly for all inputs. Not even going to bother timing it.
Challenge output:
1
u/chappell28 Oct 14 '15
I am relatively new to programming, but managed to complete the challenge in Golang; it's pretty quick and dirty, so there's probably a lot of changes that could be made to optimize it -- I'd be more than welcome to hearing any suggestions!
Code:
Output:
Benchmark:
1
u/Relayerduos Oct 14 '15
Simple solution in Python 3.5. Didn't do a timing study but it seems pretty fast even on my very slow work computer!
1
u/FlammableMarshmallow Oct 14 '15
Python3, originally wrote it brute-forcey but then read /u/Blackshell's version.
1
u/Jesus_Harold_Christ Oct 15 '15
I pretty quickly figured out the relationship between the fibonacci input and the output sequence, it's just a multiple of the regular one.
So I just threw some python code together, and this is what I came up with.
Then I saw /u/Blackshell code and I was like, "aw damn, he's caching fib numbers"
I tried his challenging number and I think my code might actually be faster.
1
u/og_king_jah Oct 15 '15
F
I might write an optimized version depending on how much time I have today.
1
u/YonkeMuffinMan Oct 15 '15
Python 2.7 Feedback is extremely welcome!
1
u/iamtechi27 Oct 15 '15
C++
My sin against computing that is me brute forcing my way through this:
GitHub repo
gets through the third challenge in 0:00.86
1
u/throwaway1231412423 Oct 15 '15 edited Oct 15 '15
JAVA. First time posting any suggestion is appreciated. It takes some time to calculate 123456789 not sure how to optimize it.
import java.util.ArrayList;
public class Fibonna {
}
1
u/ksarnek Oct 15 '15
Julia Same idea as /u/Blackshell. I implemented the Fibonacci(ish) sequence as a Julia iterator, so that I can run over them with
and if the method
lengthis defined it's also possible to use comprehensions.1
u/Panii Oct 15 '15
C, feedback very welcome.
// My fib solution #include <stdio.h>
1
u/Jambecca Oct 15 '15
Python 3.5, instantly computes anything less than around 15 digits and breaks for anything larger. Some major code smells in here.
1
u/hastyrobot Oct 15 '15
this is another javascript version. pretty naive, I don't think is leveraging anything in particular except that the effect of changing f(1)=x is to multiply the original fib sequence by x (ps: new to reddit and this forum btw)
1
u/cheers- Oct 15 '15 edited Oct 15 '15
Java
A bit slow but it works(it is rubust at least :) ). Feedback is welcomed.
Output:
Source:
1
u/Rubixdoed Oct 15 '15
Java
Feedback appreciated
Output:
1
u/ganska_bra Oct 15 '15 edited Oct 15 '15
Rust. Just started, so feedback is welcomed! Few quite ugly parts..
Output:
1
u/[deleted] Oct 15 '15
Hello! New-ish poster here! This is my approach for a C++ solution, it completed the challenge inputs near instant (I'm new to C++, so I don't know how to actually time how long it takes).
Feedback is appreciated!
1
u/SquirrelOfDooom Oct 15 '15 edited Oct 15 '15
Python 3. Late to the party again, but with fast code:
Output:
1
u/[deleted] Oct 16 '15
Python 3
1
u/jeaton Oct 16 '15
C + GMP:
1
u/ngsaip7 Oct 16 '15
Program in Ruby
1
u/aaargha Oct 16 '15 edited Oct 17 '15
C++
Calculates the lowest value of f(1) required to make a series that contain x. Solves anything that fits comfortably in a 64-bit integer in under 10ms (edit: or rather, under 1ms, after some better timing), I'll have to look at some big integer library to try the harder ones. For a more detailed description see the spoiler.
Code:
1
u/aaargha Oct 17 '15
C++ with OpenMP
A parallelized brute-force search for the correct factor, because, why not? Only finds f(1). While far slower than an efficient implementation, it's not too bad as long as f(1) is not too large.
Test runs on my i7-950 @ 3.07GHz (quad-core + HT, 8 threads):
And the you have inputs like 2976582915861023 with an f(1)=33444751863607 that will still destroy any brute-force. Will take about 40h at full blast on my machine.
Code:
1
u/Atrolantra Oct 18 '15
Fairly short in Python 2.7
It gets great times too unless I'm mistaken somehow. I'm not super experienced with timing execution so I tried the same timing method with some other python solutions here and it seems ok.
Outputs and respective times:
Code and results file can be found here.
1
u/SportingSnow21 Oct 18 '15
Go
Used a concurrent goroutine to perform lazy generation of the Fibonacci sequence.
I also created an arbitrary-precision version, code on github
Performance with inputs 0, 578, 123456789, 38695577906193299:
1
u/grangelov Oct 19 '15
Perl
1
u/jimauthors Oct 20 '15
1
u/The_Chimp Oct 24 '15 edited Oct 24 '15
Python3 solution:
A nice short one. It should run in log(n) time. Memory usage should be minimal due to the use of generators.
[source] - GitHub
1
u/Porcupine_96 Oct 27 '15
Hello! I'm new here :) What do you think about code like:
include <iostream>
using namespace std;
int main(){ ios_base::sync_with_stdio(0);
}
1
u/[deleted] Oct 27 '15 edited Oct 28 '15
Haskell in a pretty easy-to-read format, I hope:
1
u/sort_of_a_username Nov 16 '15
Python 2.7 after optimizing, finding the lowest multiple of the number you want in the regular fibonacci sequence:
1
u/briandoescode Nov 22 '15 edited Nov 22 '15
very, very late, but here's mine anyway:
1
u/lpry Dec 22 '15
Python:
Input 0:
Output: "Generated sequence: 0"
Time: 0.069 secs
Input 578:
Output: "Generated sequence: 0, 17, 17, 34, 51, 85, 136, 221, 357, 578"
Time: 0.068 secs
Input 123456789:
Output: "Generated sequence: 0, 41152263, 41152263, 82304526, 123456789"
Time: 0.089 secs
Input 2976582915861023:
Output: "Generated sequence: 0, 33444751863607, 33444751863607, 66889503727214, 100334255590821, 167223759318035, 267558014908856, 434781774226891, 702339789135747, 1137121563362638, 1839461352498385, 2976582915861023"
Time: 0.101 secs
1
u/Specter_Terrasbane Mar 18 '16
Python 2.7
Bored, and doing older challenges ... comments welcomed!
The power of itertools!
Output