任务:打印从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);
}
其他回答
你可以非常简单地使用递归和强制错误…
另外,请原谅我的c++代码非常草率。
void print_number(uint number)
{
try
{
print_number(number-1);
}
catch(int e) {}
printf("%d", number+1);
}
void main()
{
print_number(1001);
}
编译时递归!: 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);
}
也可以通过简单的动态调度来实现(在Java中也适用):
#include<iostream>
using namespace std;
class U {
public:
virtual U* a(U* x) = 0;
virtual void p(int i) = 0;
static U* t(U* x) { return x->a(x->a(x->a(x))); }
};
class S : public U {
public:
U* h;
S(U* h) : h(h) {}
virtual U* a(U* x) { return new S(new S(new S(h->a(x)))); }
virtual void p(int i) { cout << i << endl; h->p(i+1); }
};
class Z : public U {
public:
virtual U* a(U* x) { return x; }
virtual void p(int i) {}
};
int main(int argc, char** argv) {
U::t(U::t(U::t(new S(new Z()))))->p(1);
}
不懂足够的C(++)来写代码,但你可以使用递归而不是循环。为了避免这种情况,可以使用在第1000次访问后抛出异常的数据结构。例如,某种带有范围检查的列表,在每次递归时增加/减少索引。
从评论中判断,c++中似乎没有任何范围检查列表?
相反,你可以用1/n作为递归函数的参数,每次调用都减少1。从1000开始。DivisionByZero异常将停止递归
使用递归,可以使用函数指针算术替换条件:
#include <stdio.h>
#include <stdlib.h> // for: void exit(int CODE)
// function pointer
typedef void (*fptr)(int);
void next(int n)
{
printf("%d\n", n);
// pointer to next function to call
fptr fp = (fptr)(((n != 0) * (unsigned int) next) +
((n == 0) * (unsigned int) exit));
// decrement and call either ``next'' or ``exit''
fp(n-1);
}
int main()
{
next(1000);
}
注意,这里没有条件句;n !=0和n==0是无分支操作。(不过,我们在尾部调用中执行了一个分支)。