My question is: how to program a recursive sequence with PARI/GP software? For example the sequence: $$x_{n+1}=x_{n}-1, x_0=10.$$ Thank you.
2026-03-24 23:52:52.1774396372
On
On
Programming a recursive sequence with PARI/GP
391 Views Asked by Bumbble Comm https://math.techqa.club/user/bumbble-comm/detail At
3
There are 3 best solutions below
1
On
The given recurrence relation can be programmed as follows :
x(n)={if(n>0,h=x(n-1)-1);if(n==0,h=10);h}
1
On
If only some special value is needed, say $x_N$, $N=100$, then
{x(N) = local(a); a = 10; for(k=1, N, a=a-1); a}
Then for instance:
? for( n=0, 11, print( "x(", n, ") = ", x(n) ) )
x(0) = 10
x(1) = 9
x(2) = 8
x(3) = 7
x(4) = 6
x(5) = 5
x(6) = 4
x(7) = 3
x(8) = 2
x(9) = 1
x(10) = 0
x(11) = -1
(The locale can be removed safely, if a is not used around.)
If we need all terms, then it is better to store the data in a list. Please mention if this is the case.
There are a few ways, with minor variations. Here is one good way:
which gives the expected result of $\, x(n) = 10-n \,$ if $\, n\ge 0.$ It also gives $\, x(n) = 0 \,$ if $\, n<0. $ You can change that behavior to raise an error for invalid input. You can extend the recursion range:
If the recursion is computationally expensive, you may want to use Memoization which would require some changes in the code to save previous results.