Printing 1 to 1000 without loop or conditionals

Task : Print numbers from 1 to 1000 without using any loop or conditional statements. Don't just write the printf() or cout statement 1000 times.

How would you do that using C or C++?


Compile time recursion! :P

#include <iostream>
template<int N>
struct NumberGeneration{
  static void out(std::ostream& os)
  {
    NumberGeneration<N-1>::out(os);
    os << N << std::endl;
  }
};
template<>
struct NumberGeneration<1>{
  static void out(std::ostream& os)
  {
    os << 1 << std::endl;
  }
};
int main(){
   NumberGeneration<1000>::out(std::cout);
}

This one actually compiles to assembly that doesn't have any conditionals:

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

void main(int j) {
  printf("%dn", j);
  (&main + (&exit - &main)*(j/1000))(j+1);
}


Edit: Added '&' so it will consider the address hence evading the pointer errors.

This version of the above in standard C, since it doesn't rely on arithmetic on function pointers:

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

void f(int j)
{
    static void (*const ft[2])(int) = { f, exit };

    printf("%dn", j);
    ft[j/1000](j + 1);
}

int main(int argc, char *argv[])
{
    f(1);
}

#include <stdio.h>
int i = 0;
p()    { printf("%dn", ++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; }

I'm surprised nobody seems to have posted this -- I thought it was the most obvious way. 1000 = 5*5*5*8.

链接地址: http://www.djcxy.com/p/37196.html

上一篇: 用整数除以2是更好的选择?

下一篇: 无循环或条件打印1到1000