Skip to main content
10 of 10
Commonmark migration

Perl, 120 108 104 89 85

<>=~/ /;$c=$t=1;for(1..2*$'-1){$t*=$`/$_;$_%2?$s:$c+=$_&2?-$t:$t}printf"%f\n"x2,$s,$c

Ungolfed:

<> =~ / /;
$cosine = $t = 1;
for (1.. 2*$' - 1){
  $t *= $` / $_;
  ($_%2 ? $sine : $cosine) += $_&2?-$t:$t
}
printf "%.6f\n" x2, $sine, $cosine

The first line reads the input and uses regex to find a space; this automatically puts the value before the space in $` and the value after it in $'.

Now we loop from 1 to 2*n-1. $t is our term, which the loop repeatedly multiplies by x and divides by the loop's index ($_). The loop starts at 1 rather than 0 because the cosine is initialized to 1, which saved me having to deal with dividing by zero.

After updating $t, the trinary operator returns either $sine or $cosine, depending on whether the index is odd or even, and adds $t's value to it. The magic formula $_&2?-$t:$t figures whether to add or subtract this value (basically using a bitwise-and on the index and 2 to generate the repeating sequence of "add, add, subtract, subtract").

You can test-run this code at compileonline.com.

Tal
  • 1.4k
  • 7
  • 13