我认为解决方案很简单,可能与其他问题重复。对不起,如果这个答案会复制另一个。我无法找到解决方案,因为我不知道我在寻找什么。好吧,我有这个简单的函数来计算一个完整的成本总和。如何简化此功能,例如在数学函数中。
> java Turtle
Enter a command: forward
Number of steps: 5
Enter a command: right
Number of degrees: 120
Enter a command: forward
Number of steps: 5
Enter a command: right
Number of degrees: 120
Enter a command: forward
Number of steps: 5
Enter a command: quit
>
答案 0 :(得分:2)
你基本上是在计算:
fullCosts = (1 + 2 + 3 + ... + currentCount)*initialCosts
所以你可以使用:
fullCosts = initialCosts*(currentCount*(currentCount+1))/2
而不是使用for循环;因为数学!
答案 1 :(得分:2)
此功能正在计算:
fullCosts = 1*initialCosts + 2*initialCosts + ... + currentCount*initialCosts
等于:
initialCosts * (1 + 2 + ... + currentCount)
the sum of the first n
natural numbers is given by (n * (n + 1))/2
initialCosts * ((currentCount + 1) * currentCount)/2
所以我会这样做:
public int sumOfFirstNInts(int n) {
return (n * (n+1)) / 2;
}
public int getFullCosts() {
int initialCosts = 10;
int currentCount = 3;
return initialCosts * sumOfFirstNInts(currentCount);
}