Skip to main content
Stack Overflow for Teams is now Stack Internal: See how we’re powering the human intelligence layer of enterprise AI. Read more >
Code Golf

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Alternating Sign Sequence

Introduction

The sign of a number is either a +, or a - for every non-zero integer. Zero itself is signless (+0 is the same as -0). In the following sequence, we are going to alternate between the positive sign, the zero and the negative sign. The sequence starts with 1, so we write 1 with a positive sign, with zero (this one is weird, but we just multiply the number by 0) and the negative sign:

1, 0, -1

The next number is 2, and we do the same thing again:

2, 0, -2

The sequence eventually is:

1, 0, -1, 2, 0, -2, 3, 0, -3, 4, 0, -4, 5, 0, -5, 6, 0, -6, 7, 0, -7, ...

Or a more readable form:

a(0) = 1
a(1) = 0
a(2) = -1
a(3) = 2
a(4) = 0
a(5) = -2
a(6) = 3
a(7) = 0
a(8) = -3
a(9) = 4
...

The Task

Given a non-negative integer n, output the nth term of the above sequence. You can choose if you use the zero-indexed or one-indexed version.

Test cases:

Zero-indexed:

a(0) = 1
a(11) = -4
a(76) = 0
a(134) = -45
a(296) = -99

Or if you prefer one-indexed:

a(1) = 1
a(12) = -4
a(77) = 0
a(135) = -45
a(297) = -99

This is , so the submission with the smallest number of bytes wins!

Answer*

Draft saved
Draft discarded
Cancel
4
  • \$\begingroup\$ Hi and welcome to PPCG! Do you have a link I can test this (preferably online)? \$\endgroup\$ Commented Jun 2, 2016 at 2:54
  • \$\begingroup\$ @EᴀsᴛᴇʀʟʏIʀᴋ, thanks! Here's a link to an online applet thingamabob. The page looked blank for a little while, but then it showed up. \$\endgroup\$ Commented Jun 2, 2016 at 21:30
  • \$\begingroup\$ Oh cool. But how where do I put in the formula? >_> I tried pasting it into the blank, and it prompted to create a slider, but nothing else happened. \$\endgroup\$ Commented Jun 2, 2016 at 22:37
  • \$\begingroup\$ @EᴀsᴛᴇʀʟʏIʀᴋ: Over on the left-hand side, where it says "Input..." First, to initialise n, enter something like n=297 (this will give you a slider that's configured nicely). Then paste the formula into the Input box, which should now be below the n. (Make sure to hit return ;) The formula should evaluate to the nth term of the sequence, and it should change when you move the slider. \$\endgroup\$ Commented Jun 2, 2016 at 22:50

AltStyle によって変換されたページ (->オリジナル) /