任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。

用C或c++怎么做呢?


当前回答

被接受答案的c++变体:

void print(vector<int> &v, int ind)
{
    v.at(ind);
    std::cout << ++ind << std::endl;
    try
    {
        print(v, ind);
    }
    catch(std::out_of_range &e)
    {
    }
}

int main()
{
    vector<int> v(1000);
    print(v, 0);
}

其他回答

#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。

应该在任何不喜欢0 / 0的机器上工作。如果需要,可以用空指针引用替换它。程序可以在打印1到1000后失败,对吧?

#include <stdio.h>

void print_1000(int i);
void print_1000(int i) {
    int j;
    printf("%d\n", i);
    j = 1000 - i;
    j = j / j;
    i++;
    print_1000(i);
}

int main() {
    print_1000(1);
}

预处理程序滥用!

#include <stdio.h>

void p(int x) { printf("%d\n", x); }

#define P5(x) p(x); p(x+1); p(x+2); p(x+3); p(x+4);
#define P25(x) P5(x) P5(x+5) P5(x+10) P5(x+15) P5(x+20)
#define P125(x) P25(x) P25(x+50) P25(x+75) P25(x+100)
#define P500(x) P125(x) P125(x+125) P125(x+250) P125(x+375)

int main(void)
{
  P500(1) P500(501)
  return 0;
}

预处理程序(参见gcc -E input.c)非常有趣。

我们可以启动1000个线程,每个线程打印一个数字。安装OpenMPI,使用mpicxx -o 1000 1000.cpp编译,然后使用mpirun -np 1000. /1000运行。您可能需要使用limit或ulimit来增加描述符限制。注意,这将是相当慢的,除非您有大量的核心!

#include <cstdio>
#include <mpi.h>
using namespace std;

int main(int argc, char **argv) {
  MPI::Init(argc, argv);
  cout << MPI::COMM_WORLD.Get_rank() + 1 << endl;
  MPI::Finalize();
}

当然,这些数字不一定是按顺序打印的,但这个问题并不要求它们是有序的。

编辑2:

我从代码中删除了未定义的行为。谢谢@sehe的通知。

没有循环,递归,条件和所有标准C…(qsort滥用):

#include <stdio.h>
#include <stdlib.h>

int numbers[51] = {0};

int comp(const void * a, const void * b){
    numbers[0]++;
    printf("%i\n", numbers[0]);
    return 0;
}

int main()
{
  qsort(numbers+1,50,sizeof(int),comp);
  comp(NULL, NULL);
  return 0;
}