私はこのセイロンコードを持っています:
Integer fact(Integer n)
{
return (n<=1)then 1 else n*fact(n-1);
}
Integer? factorial(Integer|String|Null n)
{
Integer? num;
if(is String n)
{
num=parseInteger(n);
}
else if(is Integer n)
{
num=n;
}
else
{
num=null;
}
if(exists num)
{
if(num<0)
{
return null;
}
if(num==0)
{
return 1;
}
return (2..num).fold(1)((x,y)=>x*y);//line 1
}
else
{
return null;
}
}
shared void main()
{
print("enter a number");
value input=process.readLine()?.trimmed;
value starttime=system.milliseconds;
value fact=factorial(input);
value elapsedtime=(system.milliseconds-starttime).float/1000;
if(exists fact)
{
print("(!n)=``fact``");
print(elapsedtime);
}
else
{
print("Error, either you gave a negative number or you didn't enter an integer(or did you left the input blank ?)");
}
}
1 行目では、fold を使用して階乗を計算しています。パフォーマンスは 0.08 ~ 0.06 秒です。
1行目をこれに置き換えると:
return fact(num);
0.021 から 0.012 の間のパフォーマンスが得られます。なぜですか?
この場合、私が試した数は10でした。