粉丝私信来问一个问题,同意贴上来,但不让放图,所以手写一遍贴上来。
Given a positive integer N, compute the following sum: When N is odd:
N
2
?
(
N
?
1
)
2
+
(
N
?
2
)
2
?
(
N
?
3
)
2
+
…
+
3
2
?
2
2
+
1
2
N^2-(N-1)^2+(N-2)^2 -(N-3)^2+…+3^2-2^2+1^2
N2?(N?1)2+(N?2)2?(N?3)2+…+32?22+12 When N is even:
N
2
?
(
N
?
1
)
2
+
(
N
?
2
)
2
?
(
N
?
3
)
2
+
…
?
3
2
+
2
2
?
1
2
N^2 -(N-1)^2+(N-2)^2 -(N-3)^2+…-3^2+2^2-1^2
N2?(N?1)2+(N?2)2?(N?3)2+…?32+22?12
where
4
≤
N
≤
1
0
18
.
4 ≤ N ≤ 10^{18}.
4≤N≤1018.
1.Recursive Sum in Erlang
-
Write a recursive function practical8_id:sum(N) to compute the sum of small numbers (between 4 and 4000). -
Ask yourself whether it is better to implement this recursive program in Java or Erlang. Try to justify your reasoning with at least three points.
2.Efficient Sum in Erlang
- Write a function practical8_id:efficient(N) to efficiently compute the sum of
large numbers(between 4 and 10^18). - Compare the outputs of the efficient Erlang program with the outputs of the efficient Java program. Are they equal? Which solution is more elegant?
1.公式中间的… 是like的意思,我之前还以为是and意思,得分成两段做。这题不太严谨。 2. 偶数的公式前面缺减号,不太严谨。(和粉丝沟通过)应该为:
?
N
2
?
(
N
?
1
)
2
+
(
N
?
2
)
2
?
(
N
?
3
)
2
+
…
?
3
2
+
2
2
?
1
2
-N^2 -(N-1)^2+(N-2)^2 -(N-3)^2+…-3^2+2^2-1^2
?N2?(N?1)2+(N?2)2?(N?3)2+…?32+22?12
挺有意思的一道开放性问题。整体来说比较简单,leetcode的入门难度。
整个题目的翻译
1.在Erlang中使用递归方法
- 写一个递归函数practical8_id:sum(N)来计算求和,N为小数字(4到4000之间)。
- 问问自己用Java还是Erlang实现这个递归程序更好。
试着用至少三点来证明你的推理。
2.效率更高的Erlang Sum
- 写一个函数practical8_id:efficient(N)来高效地计算和,N为较大的数字(在4到10^18之间)。
- 比较高效Erlang程序的输出与高效Java程序的输出。他们是平等吗?哪个解决方案更优雅?
个人认为:效率更高,应该是诱导你使用尾递归
java程序
package partical8_ap114;
public class partical8_ap114 {
public static void main(String [] args) {
}
public static int sum(int x,int flag){
if(x == 0) return 0;
return sum(x-1,flag*-1) + x*x*flag;
}
public static int efficient(int x,int sum, int flag){
if(x == 0) return sum;
return efficient(x-1,sum+x*x*flag,flag*-1);
}
}
erl程序
-module(partical8_ap114).
-export([sum/1, test_sum/0, efficient/1]).
sum(N) when N >=4 andalso N =< 4000 ->
case N rem 2 of
0 ->
sum_(N,-1);
_ ->
sum_(N,1)
end.
sum_(0, _) -> 0;
sum_(N, Flag) ->
sum_(N-1, Flag * -1) + N * N * Flag.
test_sum() ->
{
-10 =:= sum(4),
15 =:= sum(5),
-21 =:= sum(6)
}.
efficient(N) when N >=4 andalso N =< 4000 ->
case N rem 2 of
0 ->
efficient(N,0,-1);
_ ->
efficient(N,0,1)
end.
efficient(0, Sum, _) -> Sum;
efficient(N, Sum, Flag) ->
efficient(N-1, Sum + N * N * Flag, Flag * -1).
开放性问题,无标准答案,如果你有更好的答案欢迎一起讨论。
|