任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
如果你打算使用编译时递归,那么你可能还想使用分治法来避免触及模板深度限制:
#include <iostream>
template<int L, int U>
struct range
{
enum {H = (L + U) / 2};
static inline void f ()
{
range<L, H>::f ();
range<H+1, U>::f ();
}
};
template<int L>
struct range<L, L>
{
static inline void f ()
{
std::cout << L << '\n';
}
};
int main (int argc, char* argv[])
{
range<1, 1000>::f ();
return 0;
}
其他回答
堆栈溢出:
#include <stdio.h>
static void print_line(int i)
{
printf("%d\n", i);
print_line(i+1);
}
int main(int argc, char* argv[])
{
//get up near the stack limit
char tmp[ 8388608 - 32 * 1000 - 196 * 32 ];
print_line(1);
}
这是一个8MB的堆栈。每次函数调用大约占用32个字节(因此是32 * 1000)。但是当我运行它时,我只得到804(因此是196 * 32;也许C运行时在堆栈中有其他部分,你也必须扣除)。
也许这太明显和容易遵循,但这是标准c++,不转储堆栈和运行在O(n)时间使用O(n)内存。
#include <iostream>
#include <vector>
using namespace std;
int main (int argc, char** args) {
vector<int> foo = vector<int>(1000);
int terminator = 0;
p:
cout << terminator << endl;
try {
foo.at(terminator++);
} catch(...) {
return 0;
}
goto p;
}
到目前为止,由于堆栈溢出,有很多不正常的退出,但还没有堆,所以这里是我的贡献:
#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(我认为有人这样做了),等等。
未经测试,但应该是香草标准C:
void yesprint(int i);
void noprint(int i);
typedef void(*fnPtr)(int);
fnPtr dispatch[] = { noprint, yesprint };
void yesprint(int i) {
printf("%d\n", i);
dispatch[i < 1000](i + 1);
}
void noprint(int i) { /* do nothing. */ }
int main() {
yesprint(1);
}
#include <stdio.h>
int show(int i) {
printf("%d\n",i);
return( (i>=1000) || show(i+1));
}
int main(int argc,char **argv) {
return show(1);
}
||操作符使递归调用短路,以显示i为>= 1000时的情况。