任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
假设程序以通常的方式(./a.out)运行,因此它有一个参数,并忽略编译器类型警告,那么:
#include <stdio.h>
#include <stdlib.h>
void main(int i) {
static void (*cont[2])(int) = { main, exit };
printf("%d\n", i);
cont[i/1000](i+1);
}
其他回答
这个实际上编译为没有任何条件的程序集:
#include <stdio.h>
#include <stdlib.h>
void main(int j) {
printf("%d\n", j);
(&main + (&exit - &main)*(j/1000))(j+1);
}
编辑:添加了'&',因此它将考虑地址,从而避免指针错误。
上面的这个版本在标准C中,因为它不依赖于函数指针的算术:
#include <stdio.h>
#include <stdlib.h>
void f(int j)
{
static void (*const ft[2])(int) = { f, exit };
printf("%d\n", j);
ft[j/1000](j + 1);
}
int main(int argc, char *argv[])
{
f(1);
}
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
class Printer
{
public:
Printer() { cout << ++i_ << "\n"; }
private:
static unsigned i_;
};
unsigned Printer::i_ = 0;
int main()
{
Printer p[1000];
}
受到Orion_G的回答和reddit讨论的启发;使用函数指针和二进制算术:
#include <stdio.h>
#define b10 1023
#define b3 7
typedef void (*fp) (int,int);
int i = 0;
void print(int a, int b) { printf("%d\n",++i); }
void kick(int a, int b) { return; }
void rec(int,int);
fp r1[] = {print, rec} ,r2[] = {kick, rec};
void rec(int a, int b) {
(r1[(b>>1)&1])(b10,b>>1);
(r2[(a>>1)&1])(a>>1,b);
}
int main() {
rec(b10,b3);
return 1;
}
到目前为止,由于堆栈溢出,有很多不正常的退出,但还没有堆,所以这里是我的贡献:
#include <cstdio>
#include <cstdlib>
#include <sys/mman.h>
#include <sys/signal.h>
#define PAGE_SIZE 4096
void print_and_set(int i, int* s)
{
*s = i;
printf("%d\n", i);
print_and_set(i + 1, s + 1);
}
void
sigsegv(int)
{
fflush(stdout); exit(0);
}
int
main(int argc, char** argv)
{
int* mem = reinterpret_cast<int*>
(reinterpret_cast<char*>(mmap(NULL, PAGE_SIZE * 2, PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, 0, 0)) +
PAGE_SIZE - 1000 * sizeof(int));
mprotect(mem + 1000, PAGE_SIZE, PROT_NONE);
signal(SIGSEGV, sigsegv);
print_and_set(1, mem);
}
这不是很好的实践,也没有错误检查(原因很明显),但我不认为这是问题的重点!
当然,还有许多其他不正常的终止选项,其中一些更简单:assert()、SIGFPE(我认为有人这样做了),等等。
这只使用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);
}