任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
#include <stdio.h>
int i = 0;
p() { printf("%d\n", ++i); }
a() { p();p();p();p();p(); }
b() { a();a();a();a();a(); }
c() { b();b();b();b();b(); }
main() { c();c();c();c();c();c();c();c(); return 0; }
我很惊讶似乎没有人张贴这个——我认为这是最明显的方式。1000 = 5*5*5*8。
其他回答
printf("%d\n", 2);
printf("%d\n", 3);
它不会打印所有的数字,但它会“打印从1到1000的数字”。暧昧的问题求赢!:)
也可以通过简单的动态调度来实现(在Java中也适用):
#include<iostream>
using namespace std;
class U {
public:
virtual U* a(U* x) = 0;
virtual void p(int i) = 0;
static U* t(U* x) { return x->a(x->a(x->a(x))); }
};
class S : public U {
public:
U* h;
S(U* h) : h(h) {}
virtual U* a(U* x) { return new S(new S(new S(h->a(x)))); }
virtual void p(int i) { cout << i << endl; h->p(i+1); }
};
class Z : public U {
public:
virtual U* a(U* x) { return x; }
virtual void p(int i) {}
};
int main(int argc, char** argv) {
U::t(U::t(U::t(new S(new Z()))))->p(1);
}
既然对bug没有限制…
int i=1; int main() { int j=i/(i-1001); printf("%d\n", i++); main(); }
或者更好(?),
#include <stdlib.h>
#include <signal.h>
int i=1;
int foo() { int j=i/(i-1001); printf("%d\n", i++); foo(); }
int main()
{
signal(SIGFPE, exit);
foo();
}
#include <iostream>
using namespace std;
template<int N>
void func()
{
func<N-1>();
cout << N << "\t";
}
template<>
void func<1>()
{
cout << 1 << "\t";
}
int main()
{
func<1000>();
cout << endl;
return 0;
}
这只使用O(log N)堆栈,并使用麦卡锡评估http://en.wikipedia.org/wiki/Short-circuit_evaluation作为其递归条件。
#include <stdio.h>
int printN(int n) {
printf("%d\n", n);
return 1;
}
int print_range(int low, int high) {
return ((low+1==high) && (printN(low)) ||
(print_range(low,(low+high)/2) && print_range((low+high)/2, high)));
}
int main() {
print_range(1,1001);
}