July 13, 2016 · Programming Arithmetic Sequence Puzzle Short-Circuit Evaluation
趣题:不用乘除法、循环、分支语句计算等差数列的和
2老师分享了一道有趣的题目:
求\( 1+2+\dots+n \),要求不能使用乘除法、
for
、while
、if else
和switch case
等关键字以及条件判断运算符 (A ? B : C
)。
一开始看到这个题确实是蒙的,只想到内嵌asm然后可以通过jmp
语句实现跳转。
经过samhjn的提醒,可以使用递归,但是还是不会解决跳转的问题。继续提醒在这里需要利用短路求值的特性,以下代码来自swx:
#include <iostream>
using namespace std;
int sum = 0;
bool calc(int i) {
sum += i;
return i && calc(i - 1);
// when i reaches 0 then the statement above returns 0 directly, without executing calc(i - 1)
}
int main(void) {
int n;
cin >> n;
calc(n);
cout << sum << endl;
return 0;
}
Foreverbell表示如果是Python的话可以提交一段base64 encoded的代码再decode并exec,orz。
iceboy表示(pow(2, n) + n) >> 1
,服。
Update (2017/7/21):
2老师在QQ空间发现的新解法:
bool ans[n][n+1];
return sizeof(ans) >> 1;