任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或c++怎么做呢?
任务:打印从1到1000的数字,不使用任何循环或条件语句。不要只写printf()或cout语句1000次。
用C或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();
}
当然,这些数字不一定是按顺序打印的,但这个问题并不要求它们是有序的。
其他回答
#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);
}
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef void(*word)(int);
word words[1024];
void print(int i) {
printf("%d\n", i);
words[i+1](i+1);
}
void bye(int i) {
exit(0);
}
int main(int argc, char *argv[]) {
words[0] = print;
words[1] = print;
memcpy(&words[2], &words[0], sizeof(word) * 2); // 0-3
memcpy(&words[4], &words[0], sizeof(word) * 4); // 0-7
memcpy(&words[8], &words[0], sizeof(word) * 8); // 0-15
memcpy(&words[16], &words[0], sizeof(word) * 16); // 0-31
memcpy(&words[32], &words[0], sizeof(word) * 32); // 0-63
memcpy(&words[64], &words[0], sizeof(word) * 64); // 0-127
memcpy(&words[128], &words[0], sizeof(word) * 128); // 0-255
memcpy(&words[256], &words[0], sizeof(word) * 256); // 0-511
memcpy(&words[512], &words[0], sizeof(word) * 512); // 0-1023
words[1001] = bye;
words[1](1);
}
令人惊讶的是,如果你放弃了“必须是C或c++”的要求,事情会变得多么简单:
Unix shell:
echo {1..1000} | tr ' ' '\n'
or
yes | nl | awk '{print $1}' | head -1000
如果你在一个没有yes命令的Unix变体上运行,使用其他进程至少生成1000行:
find / 2> /dev/null | nl | awk '{print $1}' | head -1000
or
cat /dev/zero | uuencode - | nl | awk '{print $1}' | head -1000
or
head -1000 /etc/termcap | nl -s: | cut -d: -f1
#include <stdio.h>
static void (*f[2])(int);
static void p(int i)
{
printf("%d\n", i);
}
static void e(int i)
{
exit(0);
}
static void r(int i)
{
f[(i-1)/1000](i);
r(i+1);
}
int main(int argc, char* argv[])
{
f[0] = p;
f[1] = e;
r(1);
}
易如反掌!: P
#include <iostream>
static int current = 1;
struct print
{
print() { std::cout << current++ << std::endl; }
};
int main()
{
print numbers [1000];
}