为什么我在黑客排名上"Your code did not execute within the time limits"?


static BigInteger handshake(int n) {
BigInteger fact = BigInteger.ONE;
int res = n-1;
for(int i= res ; i>0 ;i--)
{  
fact=fact.multiply(BigInteger.valueOf(i));
}
if(res==0){return BigInteger.ZERO;}
else{
return fact;
}
}

这是我创建的阶乘函数。我使用了BigInteger类,因此它可以存储较大的整数。

我认为没有办法将阶乘的计算速度提高一个数量级(尽管评论中有一些有趣的想法(。好消息是,这可能不是问题所在——你的算法不正确。

n!是对n元素进行排序的方法数,但这里的问题要简单得多。给定n人,每个人与所有其他人握手,即n-1其他人。然后我们把它一分为二,因为爱丽丝和鲍勃握手和鲍勃和爱丽丝握手完全一样。所以,长话短说,你不需要找到n的阶乘。由于对于给定的输入范围,n * (n-1)/2完全在long的限制范围内,因此也不必再纠缠于BigInteger

private static long handshake(long n) {
return n * (n - 1L) / 2L;
}

最新更新