Sine Series

Problem

Read an angle x in radians and a count n. Print the sum of the first n terms of x - x^3/3! + x^5/5! - x^7/7! + ... with 4 digits after the decimal point. This sum is an estimate of sin(x).

Constraints

  • -10 <= x <= 10, 1 <= n <= 100

Examples

Input

1 8

Output

0.8415

Solutions

Best approachTime O(n)Space O(1)

From one term to the next, the power of x grows by 2, the factorial grows by two more factors (2k and 2k + 1), and the sign flips. So the next term is the previous term times -x * x / ((2k) * (2k + 1)).

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Estimate sin(x) with the first n terms of x - x^3/3! + x^5/5! - ...
 * Input   : A decimal number x (in radians) and an integer n on one line.
 * Output  : The estimate with 4 digits after the decimal point.
 * Approach: Multiply each term by -x * x / ((2k) * (2k + 1)).
 * Time    : O(n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Locale;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // Locale.US makes the scanner read a dot as the decimal separator.
        Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
        double x = scanner.nextDouble();
        int count = scanner.nextInt();

        // Step 1: The first term is x. The sum starts with it.
        double term = x;
        double sum = x;

        // Step 2: Calculate the next terms. Each term changes sign and has x * x more and two more factors in the factorial.
        for (int k = 1; k < count; k++) {
            // Step 3: Example: x^3 / 3! = x / 1! * (-x * x) / (2 * 3). The minus sign makes the signs alternate.
            term = term * (-x * x) / ((2 * k) * (2 * k + 1));
            sum = sum + term;
        }

        // Step 4: Print the sum with 4 digits after the decimal point.
        System.out.println(String.format(Locale.US, "%.4f", sum));
    }
}
Hints (2)
  1. Compare x^3 / 3! with x^5 / 5!.
  2. Which factor changes the sign?