hdu1042 N!(大数求阶乘)
Posted fqfzs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu1042 N!(大数求阶乘)相关的知识,希望对你有一定的参考价值。
N!
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 94583 Accepted Submission(s): 28107
Problem Description
Given an integer N(0 ≤ N ≤ 10000), your task is to calculate N!
Input
One N in one line, process to the end of file.
Output
For each N, output N! in one line.
Sample Input
1
2
3
Sample Output
1
2
6
数据范围比较大,要用到大数。
c++
1 #include<bits/stdc++.h> 2 using namespace std; 3 string Multiply(string s,int x) 4 { 5 reverse(s.begin(),s.end()); 6 int cmp=0; 7 for(int i=0; i<s.size(); i++) 8 { 9 cmp=(s[i]-‘0‘)*x+cmp; 10 s[i]=(cmp%10+‘0‘); 11 cmp/=10; 12 } 13 while(cmp) 14 { 15 s+=(cmp%10+‘0‘); 16 cmp/=10; 17 } 18 reverse(s.begin(),s.end()); 19 return s; 20 } 21 int main() 22 { 23 int n; 24 while(~scanf("%d",&n)) 25 { 26 string sum="1"; 27 for(int i=1; i<=n; i++) 28 { 29 sum=Multiply(sum,i); 30 } 31 cout<<sum<<endl; 32 } 33 return 0; 34 }
Java
1 import java.math.BigInteger; 2 import java.util.Scanner; 3 public class Main { 4 public static void main(String[] args) { 5 Scanner cin = new Scanner(System.in ); 6 while(cin.hasNext()) { 7 int n=cin.nextInt(); 8 BigInteger sum=BigInteger.valueOf(1); 9 for(int i=1;i<=n;i++) 10 { 11 BigInteger temp=BigInteger.valueOf(i); 12 sum=sum.multiply(temp); 13 } 14 System.out.println(sum); 15 16 } 17 } 18 }
PS:这题好像还是Java比较快。。。
以上是关于hdu1042 N!(大数求阶乘)的主要内容,如果未能解决你的问题,请参考以下文章