Fibonacci sequence up to first 256 elements
Show older comments
I want to generate first 256 fibonacci sequence elments . the code is repeating a fixed number after some terms, I think that we can use maximum of uint 64 and if a number gets begger we just stuck or is there any other reason or mistake in the code.
clear
format long g
n(1) =uint64(1);
n(2) = 1;
k = 3;
while k <= 256
n(k) = [n(k-2) + n(k-1)];
k = k + 1;
end
ff=mod(n,256);
%fprintf('%g,',n)
what I m getting is
Columns 91 through 105
69 189 2 255 255 255 255 255 255 255 255 255 255 255 255
Columns 106 through 120
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
Columns 121 through 135
4 Comments
KALYAN ACHARJYA
on 10 Aug 2019
Edited: KALYAN ACHARJYA
on 10 Aug 2019
I have deleted my answer.
@Guillaume Comments Moved here
I don't have the symbolic toolbox so can't test, but I suspect that calculating the whole sum as symbolic would be very slow.
@sadiqa, I assume you mean binary bitxor, because using the logical xor, it's very easy to know the result, xor(fibo_num, something) is simply going to be ~something since from the point of view of plain logical xor fibo_num is always true.
Guillaume
on 10 Aug 2019
What we're missing here is an explanation of the need for this (or is it homework?).
Also. note that the fibonacci sequence modulo any number is periodical (for modulo 256, if I got it right the period is 384).
sadiqa ilyas
on 10 Aug 2019
John D'Errico
on 10 Aug 2019
Note that the periodicity of the Fibonacci sequence is not actually relevant, since as long as you work in mod 256 always, there is no overflow.
Accepted Answer
More Answers (1)
Guillaume
on 10 Aug 2019
As for your question,
% Calculating first 256 terms.
% As soon as the values are >flintmax, they're just approximate
x = [1, zeros(1, 255)];
fib = filter(1, [1, -1, -1], x);
find(fib > flintmax, 1) %when does it overflow double?
find(fib > intmax('uint64'), 1) %when does it overflow uint64?
shows that the fibonacci sequence overflows flintmax at element 79, so from then on the values are approximations when stored as double.
It also shows that the sequence overflows uint64 at element 94. In matlab, integer overflows simply returns intmax, so from element 94, your sequence is simply going to be intmax('uint64'). And indeed, mod(intmax('uint64'), 256) is 255, so there's nothing surprising in your result.
So, there's no way that you can calculate more than 93 terms as a 64-bit integer. In fact, if you want to go to 256 terms, you'll need around 180 bits to store it as an integer.
However, since it looks like you're interested in computing it in the ring of integers modulo 256, there may be an algorithm that allows you to do that directly without computing the actual terms. Have you searched for it?
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!