30
3
Let's use the four basic operations, addition +
, multiplication *
, subtraction -
and division /
(float, not integer).
Stewie's sequence is defined as follows:
x = [x(1), x(2)] // Two initial numbers (one indexed)
x(3) = x(1) + x(2)
x(4) = x(2) * x(3)
x(5) = x(3) - x(4)
x(6) = x(4) / x(5)
x(7) = x(5) + x(6)
... and so on.
Challenge:
Take two non-negative integers (x(1), x(2)
), and one positive integer N
as input.
x(1)
and x(2)
will be the two first numbers of your sequence, and N
will be the length of the sequence you must output. (You can choose to have the list 0-based, in which case N
will be one less than the length).
- You can not assume that
x(2) >= x(1)
. N
will always be>2
if 1-based, (>1
if 0-based).- You do not have to handle division by zero errors.
- Note the 2nd test case. You will not get
0, 1
, andN=6
as input, since that will result in division by zero, but you must support0, 1
andN=5
.
- Note the 2nd test case. You will not get
- Assume only valid input will be given.
- The input and output can be on any convenient format, but you must support at least 3 digits after the decimal points if the output is non-integer.
Test cases:
1 3
8
1, 3, 4, 12, -8, -1.5, -9.5, 14.25
0 1
5
0, 1, 1, 1, 0 // N=6 would give division by zero error. You don't need to handle that case.
1 0
9
1, 0, 1, 0, 1, 0, 1, 0, 1
6 3
25
6, 3, 9, 27, -18, -1.5, -19.5, 29.25, -48.75, -0.6, -49.35, 29.61, -78.96, -0.375, -79.335, 29.7506, -109.086, -0.272727, -109.358, 29.825, -139.183, -0.214286, -139.398, 29.8709, -169.269
Can a function take x(1) and x(2) as a list? Or seperate arguments? – FlipTack – 2016-11-25T22:31:36.300
Whatever is convenient for you :) – Stewie Griffin – 2016-11-25T22:32:24.887
Can
N
be 0-based? So take as inputs 1 less than the N shown in your examples. I guess taking N-2 is too much to ask for... :-P – Luis Mendo – 2016-11-25T22:44:49.350When you write output can be on any convenient format, does that include a list with the final element in the beginning and the start-elements at the end (a reversed list)? – Emigna – 2016-11-25T22:50:22.793
@LuisMendo N can be zero-based. And you're right about that second part :) – Stewie Griffin – 2016-11-25T22:57:43.417
1@Emigna, no I think that's a bit of a stretch... The numbers should be in the correct order – Stewie Griffin – 2016-11-25T22:58:33.280
I'm working on an x86 assembly-language function (smallest machine-code) answer. Since I can't just "return" a list, the caller has to pass a buffer as well as a length. Can I take x1 and x2 as
float
s already stored in the buffer? (i.e. a function that continues a sequence for N more values). Otherwise I'll just take them as floats or integers on the stack or in registers, depending on whether I decide to go for 64-bit or 32-bit code, and System V calling convention or custom. – Peter Cordes – 2016-11-27T08:10:51.410