任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
这只使用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);
}
其他回答
一个脏代码:s
使用xor和数组的函数指针。
#include <stdio.h>
#include <stdlib.h>
typedef void (*fn)(int);
int lst[1001];
void print (int n)
{
printf ("%d ", n+1);
go (n+1);
}
void go (int n)
{
((fn)(((long)print)^((long)lst[n])))(n);
}
int main ()
{
lst[1000] = ((long)print)^((long)exit);
go (0);
}
#include "stdafx.h"
static n=1;
class number {
public:
number () {
std::cout << n++ << std::endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
number X[1000];
return 0;
}
这是我的两个解。第一个是c#,第二个是C语言:
C#:
const int limit = 1000;
Action<int>[] actions = new Action<int>[2];
actions[0] = (n) => { Console.WriteLine(n); };
actions[1] = (n) => { Console.WriteLine(n); actions[Math.Sign(limit - n-1)](n + 1); };
actions[1](0);
C:
#define sign(x) (( x >> 31 ) | ( (unsigned int)( -x ) >> 31 ))
void (*actions[3])(int);
void Action0(int n)
{
printf("%d", n);
}
void Action1(int n)
{
int index;
printf("%d\n", n);
index = sign(998-n)+1;
actions[index](++n);
}
void main()
{
actions[0] = &Action0;
actions[1] = 0; //Not used
actions[2] = &Action1;
actions[2](0);
}
我重新制定了比尔提出的伟大惯例,使其更加普遍:
void printMe ()
{
int i = 1;
startPrintMe:
printf ("%d\n", i);
void *labelPtr = &&startPrintMe + (&&exitPrintMe - &&startPrintMe) * (i++ / 1000);
goto *labelPtr;
exitPrintMe:
}
更新:第二种方法需要2个功能:
void exitMe(){}
void printMe ()
{
static int i = 1; // or 1001
i = i * !!(1001 - i) + !(1001 - i); // makes function reusable
printf ("%d\n", i);
(typeof(void (*)())[]){printMe, exitMe} [!(1000-i++)](); // :)
}
对于这两种情况,都可以通过简单地调用来启动打印
printMe();
已为GCC 4.2测试。
编译时递归!: 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);
}