任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
当前回答
既然对bug没有限制…
int i=1; int main() { int j=i/(i-1001); printf("%d\n", i++); main(); }
或者更好(?),
#include <stdlib.h>
#include <signal.h>
int i=1;
int foo() { int j=i/(i-1001); printf("%d\n", i++); foo(); }
int main()
{
signal(SIGFPE, exit);
foo();
}
其他回答
我觉得这个答案会很简单,很容易理解。
int print1000(int num=1)
{
printf("%d\n", num);
// it will check first the num is less than 1000.
// If yes then call recursive function to print
return num<1000 && print1000(++num);
}
int main()
{
print1000();
return 0;
}
我想知道面试官是不是说错了一个问题:不使用循环,计算从1到1000(或从n到m的任意数字)的和。它还教会我们如何分析问题。在C中从1到1000s打印#s总是依赖于在生产程序中可能不会使用的技巧(Main中的尾部递归,计算真实性的副作用,或预处理和模板技巧)。
这将是一个很好的抽查,看看你是否接受过数学训练,因为关于高斯和他的解的古老故事可能对任何接受过数学训练的人都很熟悉。
也可以通过简单的动态调度来实现(在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);
}
#include<iostream>
#include<stdexcept>
using namespace std;
int main(int arg)
{
try
{
printf("%d\n",arg);
int j=1/(arg-1000);
main(arg+1);
}
catch(...)
{
exit(1);
}
}
受到Orion_G的回答和reddit讨论的启发;使用函数指针和二进制算术:
#include <stdio.h>
#define b10 1023
#define b3 7
typedef void (*fp) (int,int);
int i = 0;
void print(int a, int b) { printf("%d\n",++i); }
void kick(int a, int b) { return; }
void rec(int,int);
fp r1[] = {print, rec} ,r2[] = {kick, rec};
void rec(int a, int b) {
(r1[(b>>1)&1])(b10,b>>1);
(r2[(a>>1)&1])(a>>1,b);
}
int main() {
rec(b10,b3);
return 1;
}