博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HackerRank Extra long factorials
阅读量:4700 次
发布时间:2019-06-09

本文共 1768 字,大约阅读时间需要 5 分钟。

今天在HackerRank上翻到一道高精度题,于是乎就写了个高精度的模板,说是模板其实就只有乘法而已。

Extra long factorials

Authored by  on Jun 16 2015

Problem Statement

You are given an integer N. Print the factorial of this number.

 

N!=N×(N1)×(N2)××3×2×1

 

Note: Factorials of N>20 can't be stored even in a 64bit long long variable. Big integers must be used for such calculations. Languages like Java, Python, Ruby etc. can handle big integers but we need to write additional code in C/C++ to handle such large values.

We recommend solving this challenge using BigIntegers.

Input Format 

Input consists of a single integer N.

Constraints 

1N100

Output Format 

Output the factorial of N.

Sample Input

25

Sample Output

15511210043330985984000000 ------------------------------------------------------------------------------------- 从前看C++ Primer时,看到Constructor处发现有很多方便的feature,但一般也不写Class,大多忘却了。这回用了一下,还不错。
const int N(10000);int tmp[N];struct BigInt{
int d[N], len; BigInt(int n){
len=!n; for(int tmp=n; tmp; len++, tmp/=10); for(int i=len-1; i>=0; i--) d[i]=n%10, n/=10; } BigInt(){} void multi(const BigInt &n){
memset(tmp, 0, sizeof(tmp)); for(int i=0; i

 

 注意到这里写了两个Constructor,一个带参数的BigInt(int n)以及一个不带参数的BigInt()。如果一个class里没写constructor的话其实还是带有一个default constructor的,这里就是BigInt::BigInt(),但如果定义了Constructor的话default constructor就会被覆盖,所以这里还要将BigInt()显式(explicitly)定义一下,否则 BigInt a;这种声明变量的方式就会报错。

 

和constructor有关的概念还有type conversion。我们定义了BigInt::BigInt(int n)后求阶乘就可很简洁地写成  

BigInt res(1);    for(int i=2; i<=n; i++){
res.multi(i); }

我们将int型的变量i传递给函数BigInt::void multi(const BigInt &n)时,int将会自动转换成BigInt,之所以可以这样正是由于我们定义了constructor BigInt(int n) 

 

转载于:https://www.cnblogs.com/Patt/p/4745152.html

你可能感兴趣的文章
解决在vue中,自用mask模态框出来后,下层的元素依旧可以滑动的问题
查看>>
修改node节点名称
查看>>
PAT(B) 1014 福尔摩斯的约会(Java)
查看>>
PAT甲级题解-1123. Is It a Complete AVL Tree (30)-AVL树+满二叉树
查看>>
项目开发总结报告(GB8567——88)
查看>>
SSH加固
查看>>
端口扫描base
查看>>
iOS IM开发的一些开源、框架和教程等资料
查看>>
FansUnion:共同写博客计划终究还是“流产”了
查看>>
python 二维字典
查看>>
pip 警告!The default format will switch to columns in the future
查看>>
Arrays类学习笔记
查看>>
实验吧之【天下武功唯快不破】
查看>>
2019-3-25多线程的同步与互斥(互斥锁、条件变量、读写锁、自旋锁、信号量)...
查看>>
win7-64 mysql的安装
查看>>
dcm4chee 修改默认(0002,0013) ImplementationVersionName
查看>>
maven3在eclipse3.4.2中创建java web项目
查看>>
发布时间 sql语句
查看>>
黑马程序员 ExecuteReader执行查询
查看>>
记一些从数学和程序设计中体会到的思想
查看>>