任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
我不想破坏它,但递归和循环在机器级别本质上是相同的事情。
区别在于JMP/JCC与CALL指令的使用。两者都有大致相同的周期时间,并刷新指令管道。
我最喜欢的递归技巧是手工编写返回地址的PUSH,并对函数使用JMP。然后函数正常工作,并在结束时返回,但返回到其他地方。这对于更快地解析非常有用,因为它减少了指令管道刷新。
最初的海报可能是一个完整的展开,这是模板的人想出的;或者将页内存放入终端,如果您确切地知道终端文本存储在哪里。后者需要大量的洞察力和风险,但几乎不需要计算能力,并且代码没有像连续1000个打印文件那样的麻烦。
其他回答
我对这个美妙的答案集的一点贡献(它返回零):
#include <stdio.h>
int main(int a)
{
return a ^ 1001 && printf("%d\n", main(a+1)) , a-1;
}
逗号运算符为FTW \o/
令人惊讶的是,如果你放弃了“必须是C或c++”的要求,事情会变得多么简单:
Unix shell:
echo {1..1000} | tr ' ' '\n'
or
yes | nl | awk '{print $1}' | head -1000
如果你在一个没有yes命令的Unix变体上运行,使用其他进程至少生成1000行:
find / 2> /dev/null | nl | awk '{print $1}' | head -1000
or
cat /dev/zero | uuencode - | nl | awk '{print $1}' | head -1000
or
head -1000 /etc/termcap | nl -s: | cut -d: -f1
c++利用RAII
#include <iostream>
using namespace std;
static int i = 1;
struct a
{
a(){cout<<i++<<endl;}
~a(){cout<<i++<<endl;}
}obj[500];
int main(){return 0;}
C语言开发宏
#include <stdio.h>
#define c1000(x) c5(c5(c5(c4(c2(x)))))
#define c5(x) c4(x) c1(x) //or x x x x x
#define c4(x) c2(c2(x)) //or x x x x
#define c2(x) c1(x) c1(x) //or x x
#define c1(x) x
int main(int i){c1000(printf("%d\n",i++);)return 0;}
编辑:还有一个,这个很简单
#include <stdio.h>
#define p10(x) x x x x x x x x x x
int main(int i){p10(p10(p10(printf("%d\n",i++);)))return 0;}
解析:选C
编辑:此c代码包含<=和?:操作符
#include <stdio.h>
int main(int i){return (i<=1000)?main(printf("%d\n",i++)*0 + i):0;}
以下是我知道的三个解决方案。不过,第二种说法可能存在争议。
// compile time recursion
template<int N> void f1()
{
f1<N-1>();
cout << N << '\n';
}
template<> void f1<1>()
{
cout << 1 << '\n';
}
// short circuiting (not a conditional statement)
void f2(int N)
{
N && (f2(N-1), cout << N << '\n');
}
// constructors!
struct A {
A() {
static int N = 1;
cout << N++ << '\n';
}
};
int main()
{
f1<1000>();
f2(1000);
delete[] new A[1000]; // (3)
A data[1000]; // (4) added by Martin York
}
[编辑:(1)和(4)只能用于编译时常数,(2)和(3)也可以用于运行时表达式-结束编辑。]]
我错过了所有的乐趣,所有好的c++答案都已经贴出来了!
这是我能想到的最奇怪的事情,我不认为它是合法的C99:p
#include <stdio.h>
int i = 1;
int main(int argc, char *argv[printf("%d\n", i++)])
{
return (i <= 1000) && main(argc, argv);
}
另一个,有点欺骗:
#include <stdio.h>
#include <boost/preprocessor.hpp>
#define ECHO_COUNT(z, n, unused) n+1
#define FORMAT_STRING(z, n, unused) "%d\n"
int main()
{
printf(BOOST_PP_REPEAT(1000, FORMAT_STRING, ~), BOOST_PP_ENUM(LOOP_CNT, ECHO_COUNT, ~));
}
最后一个想法,同样的欺骗:
#include <boost/preprocessor.hpp>
#include <iostream>
int main()
{
#define ECHO_COUNT(z, n, unused) BOOST_PP_STRINGIZE(BOOST_PP_INC(n))"\n"
std::cout << BOOST_PP_REPEAT(1000, ECHO_COUNT, ~) << std::endl;
}