Advertisement
dimipan80

Calculate 1 + 1!/X + 2!/X^2 + … + N!/X^N

Aug 8th, 2014
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.04 KB | None | 0 0
  1. /* Write a program that, for a given two integer numbers n and x,
  2.  * calculates the sum S = 1 + 1!/x + 2!/x^2 + … + n!/x^n. Use only one loop.
  3.  * Print the result with 5 digits after the decimal point. */
  4.  
  5. import java.util.Locale;
  6. import java.util.Scanner;
  7.  
  8. public class _05_CalculateTheSumOfFractions {
  9.  
  10.     public static void main(String[] args) {
  11.         // TODO Auto-generated method stub
  12.         Locale.setDefault(Locale.ROOT);
  13.         Scanner scanner = new Scanner(System.in);
  14.         System.out.print("Enter a whole positive number for N: ");
  15.         int numN = scanner.nextInt();
  16.         System.out.print("Enter other whole number for X: ");
  17.         int numX = scanner.nextInt();
  18.         scanner.close();
  19.  
  20.         if (numN > 0) {
  21.             double sum = 1;
  22.             double nominator = 1;
  23.             double denominator = 1;
  24.             for (int i = 1; i <= numN; i++) {
  25.                 nominator *= i;
  26.                 denominator *= numX;
  27.                 sum += nominator / denominator;
  28.             }
  29.  
  30.             System.out.printf("The Sum of these Fractions is: %.5f!\n", sum);
  31.         } else {
  32.             System.out.println("Error! - Invalid Input number N!!!");
  33.         }
  34.     }
  35.  
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement