Mandatory awk
-based solution (where for simplicity I will assume n>2
):
awk -v n=9 'BEGIN{q=1; printf "0,*,"; for (i=2;i<n;i++) {s=q+r;r=q;q=s; printf "%s%s",i%2?"*":s,i==n-1?"\n":","}}'
The user input is stored in the variable n
and passed to awk
via the command-line argument -v n=number
.
In order to exit immediately if n<3
:
awk -v n=9 'BEGIN{if (n<3) exit; q=1; printf "0,*,"; for (i=2;i<n;i++) {s=q+r;r=q;q=s; printf "%s%s",i%2?"*":s,i==n-1?"\n":","}}'
Explanation
awk
is a text-processing tool, we are "creatively misusing" it. Therefore, everything happens inside the BEGIN
block which usually contains code executed before the first input file is processed.
The syntax itself is very C-like, so we
- print the first two terms of the series (which are fixed since we assume
n>2
): printf "0,*,"
- loop from
2
to n-1
and calculate the Fibonaccy number s
as sum of the two previous ones q
and r
, and update q
and r
- print either
*
if i
is even, or the current Fibonacci number s
if it is not (i%2?"*":s
)
- and print either a
,
or a newline after that, depending on whether we have reached the end of the loop (i==n-1
) or not.
*
s on the consecutive numbers.0,*,1,*,3,*,8,*,21