About factorial calculation

Source: Internet
Author: User

In this example, we use the while loop method to calculate 1 + 1/2! + 1/3! +... 1/20!

At the beginning, I thought the factorial could be directly written, like this.

package com.lixiyu;public class Count1 {public static void main(String[] args){    int i=1;    int sum=0;    while(i<=20){        sum+=(1/i!);        i++;       }    System.out.println("sum="+sum);}}

It is always at the factorial position "!". Error message: java Syntax error on token "! ", Delete this token

I thought about it later! It cannot be used directly. After Google, we found that a mathematical package was called: java. math. BigDecimal.

However, I read the API documentation and did not clarify this usage. Half-Knowledge

First, paste the source code and ponder over it.

Package com. lixiyu; import java. math. bigDecimal; public class Count1 {public static void main (String args []) {BigDecimal sum = new BigDecimal (0.0); // and BigDecimal factorial = new BigDecimal (1.0 ); // The calculation result of the factorial is int I = 1; // the incremental while (I <= 20) {sum = sum. add (factorial); // accumulate the factorial and ++ I; // I add 1 factorial = factorial. multiply (new BigDecimal (1.0/I); // calculate a factorial} System. out. println ("1 + 1/2! + 1/3! ... 1/20! The calculation result of is equal to \ n "+ sum); // output the calculation result }}

Compile the running result:

1 + 1/2! + 1/3! ... 1/20! The calculation result of is equal to: 1. 7182818284590452236725888 .............


This article is from the "ToBeContinued" blog, please be sure to keep this source http://leexy.blog.51cto.com/4136883/1302890

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.