How to resolve the algorithm Fibonacci sequence step by step in the PARI/GP programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Fibonacci sequence step by step in the PARI/GP programming language
Table of Contents
Problem Statement
The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
Write a function to generate the nth Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: support for negative n in the solution is optional.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Fibonacci sequence step by step in the PARI/GP programming language
Source code in the pari/gp programming language
fibonacci(n)
fib(n)=([1,1;1,0]^n)[1,2]
fib(n)=my(phi=(1+sqrt(5))/2);round((phi^n-phi^-n)/sqrt(5))
fib(n)=round(((1+sqrt(5))/2)^n/sqrt(5))
fib(n)=imag(quadgen(5)^n)
fib(n)=my(phi=quadgen(5));(phi^n-(-1/phi)^n)/(2*phi-1)
fib(n)=polcoeff(x/(1-x-x^2)+O(x^(n+1)),n)
fib(n)={
if(n<=0,
if(n,(-1)^(n+1)*fib(n),0)
,
my(v=lucas(n-1));
(2*v[1]+v[2])/5
)
};
lucas(n)={
if (!n, return([2,1]));
my(v=lucas(n >> 1), z=v[1], t=v[2], pr=v[1]*v[2]);
n=n%4;
if(n%2,
if(n==3,[v[1]*v[2]+1,v[2]^2-2],[v[1]*v[2]-1,v[2]^2+2])
,
if(n,[v[1]^2+2,v[1]*v[2]+1],[v[1]^2-2,v[1]*v[2]-1])
)
};
fib(n)={
if(n<2,
n
,
fib(n-1)+fib(n)
)
};
fib(n)={
if(n<2,
n
,
my(s=self());
s(n-2)+s(n-1)
)
};
apply(n->if(n<2,n,my(s=self());s(n-2)+s(n-1)), [1..10])
F=[];
fib(n)={
if(n>#F,
F=concat(F, vector(n-#F));
F[n]=fib(n-1)+fib(n-2)
,
if(n<2,
n
,
if(F[n],F[n],F[n]=fib(n-1)+fib(n-2))
)
);
}
fib(n)={
if(n<0,return((-1)^(n+1)*fib(n)));
my(a=0,b=1,t);
while(n,
t=a+b;
a=b;
b=t;
n--
);
a
};
fib(n)=n--;polchebyshev(n,2,I/2)*I^n;
fib(n)=abs(polchebyshev(n-1,2,I/2));
matantihadamard(n)={
matrix(n,n,i,j,
my(t=j-i+1);
if(t<1,t%2,t<3)
);
}
fib(n)=matdet(matantihadamard(n))
fib(n)=
{
my(g=2^(n+1)-1);
sum(i=2^(n-1),2^n-1,
bitor(i,i<<1)==g
);
}
fib(n)=my(k=0);while(n--,k++;while(!issquare(5*k^2+4)&&!issquare(5*k^2-4),k++));k
You may also check:How to resolve the algorithm Return multiple values step by step in the PHP programming language
You may also check:How to resolve the algorithm URL encoding step by step in the Bracmat programming language
You may also check:How to resolve the algorithm Soundex step by step in the Prolog programming language
You may also check:How to resolve the algorithm Non-continuous subsequences step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Truth table step by step in the J programming language