关于c ++:在没有循环或条件的情况下打印1到1000

Printing 1 to 1000 without loop or conditionals

任务:打印数字从1到1000,不使用任何循环或条件语句。 不要只写1000次printf()cout语句。

你会怎么用C或C ++做到这一点?


这个实际上编译为没有任何条件的程序集:

1
2
3
4
5
6
7
8
#include <stdio.h>
#include <stdlib.h>

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

编辑:添加'&',因此它将考虑地址,从而避免指针错误。

这个版本的上面标准C,因为它不依赖于函数指针上的算术:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
#include <stdlib.h>

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

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

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


编译时间递归! :P

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#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);
}


1
2
3
4
5
6
7
8
#include <stdio.h>
int i = 0;
p()    { printf("%d
"
, ++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; }

我很惊讶似乎没有人发布这个 - 我认为这是最明显的方式。 1000 = 5*5*5*8.


看起来它不需要使用循环

1
2
printf("1 10 11 100 101 110 111 1000
"
);


以下是我所知道的三种解决方案。第二个可能是有争议的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// compile time recursion
template<int N> void f1()
{
    f1<N-1>();
    cout << N << '
'
;
}

template<> void f1<1>()
{
    cout << 1 << '
'
;
}

// short circuiting (not a conditional statement)
void f2(int N)
{
    N && (f2(N-1), cout << N << '
'
);
}

// constructors!
struct A {
    A() {
        static int N = 1;
        cout << N++ << '
'
;
    }
};

int main()
{
    f1<1000>();
    f2(1000);
    delete[] new A[1000]; // (3)
    A data[1000]; // (4) added by Martin York
}

[编辑:(1)和(4)只能用于编译时常量,(2)和(3)可用于运行时表达式太结束编辑。 ]


我没有写1000次printf语句!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
printf("1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"
);

别客气 ;)


1
2
3
4
printf("%d
"
, 2);
printf("%d
"
, 3);

它不会打印所有数字,但会打印"从1到1000打印数字"。赢得暧昧的问题! :)


触发致命错误!这是文件countup.c:

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
#define MAX 1000
int boom;
int foo(n) {
    boom = 1 / (MAX-n+1);
    printf("%d
"
, n);
    foo(n+1);
}
int main() {
    foo(1);
}

编译,然后在shell提示符下执行:

1
2
3
4
5
6
7
8
9
10
11
12
$ ./countup
1
2
3
...
996
997
998
999
1000
Floating point exception
$

这确实打印了从1到1000的数字,没有任何循环或条件!


使用系统命令:

1
system("/usr/bin/seq 1000");


未经测试,但应该是香草标准C:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void yesprint(int i);
void noprint(int i);

typedef void(*fnPtr)(int);
fnPtr dispatch[] = { noprint, yesprint };

void yesprint(int i) {
    printf("%d
"
, i);
    dispatch[i < 1000](i + 1);
}

void noprint(int i) { /* do nothing. */ }

int main() {
    yesprint(1);
}


与其他人相比有点无聊,但可能是他们正在寻找的东西。

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>

int f(int val) {
    --val && f(val);
    return printf("%d
"
, val+1);
}

void main(void) {
    f(1000);
}


该任务从未指定程序必须在1000之后终止。

1
2
3
4
5
6
7
8
9
void f(int n){
   printf("%d
"
,n);
   f(n+1);
}

int main(){
   f(1);
}

(如果你运行./a.out而没有额外的参数,可以缩短到这个)

1
2
3
4
5
void main(int n) {
   printf("%d
"
, n);
   main(n+1);
}


非常简单! :P

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

static int current = 1;

struct print
{
    print() { std::cout << current++ << std::endl; }
};

int main()
{
    print numbers [1000];
}


1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
#define Out(i)       printf("%d
", i++);
#define REP(N)       N N N N N N N N N N
#define Out1000(i)   REP(REP(REP(Out(i))));
void main()
{
 int i = 1;
 Out1000(i);
}


我们可以启动1000个线程,每个线程打印一个数字。安装OpenMPI,使用mpicxx -o 1000 1000.cpp进行编译并使用mpirun -np 1000 ./1000运行。您可能需要使用limitulimit来增加描述符限制。请注意,这将是相当慢的,除非您有大量的核心!

1
2
3
4
5
6
7
8
9
#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();
}

当然,这些数字不一定按顺序打印,但问题不需要订购。


用普通C:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<stdio.h>

/* prints number  i */
void print1(int i) {
    printf("%d
"
,i);
}

/* prints 10 numbers starting from i */
void print10(int i) {
    print1(i);
    print1(i+1);
    print1(i+2);
    print1(i+3);
    print1(i+4);
    print1(i+5);
    print1(i+6);
    print1(i+7);
    print1(i+8);
    print1(i+9);
}

/* prints 100 numbers starting from i */
void print100(int i) {
    print10(i);
    print10(i+10);
    print10(i+20);
    print10(i+30);
    print10(i+40);
    print10(i+50);
    print10(i+60);
    print10(i+70);
    print10(i+80);
    print10(i+90);
}

/* prints 1000 numbers starting from i */
void print1000(int i) {
    print100(i);
    print100(i+100);
    print100(i+200);
    print100(i+300);
    print100(i+400);
    print100(i+500);
    print100(i+600);
    print100(i+700);
    print100(i+800);
    print100(i+900);
}


int main() {
        print1000(1);
        return 0;
}

当然,您可以为其他基础实现相同的想法(2:print2 print4 print8 ...),但这里的数字1000建议基数10.您还可以减少添加中间函数的行数:print2() print10() print20() print100() print200() print1000()和其他等效替代品。


只需将std :: copy()与特殊迭代器一起使用即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include
#include <iostream>
#include <iterator>

struct number_iterator
{
    typedef std::input_iterator_tag iterator_category;
    typedef int                     value_type;
    typedef std::size_t             difference_type;
    typedef int*                    pointer;
    typedef int&                    reference;

    number_iterator(int v): value(v)                {}
    bool operator != (number_iterator const& rhs)   { return value != rhs.value;}
    number_iterator operator++()                    { ++value; return *this;}
    int operator*()                                 { return value; }
    int value;
};



int main()
{
    std::copy(number_iterator(1),
              number_iterator(1001),
              std::ostream_iterator<int>(std::cout,""));
}


函数指针(ab)使用。没有预处理器魔法来增加输出。 ANSI C

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>

int i=1;

void x10( void (*f)() ){
    f(); f(); f(); f(); f();
    f(); f(); f(); f(); f();
}

void I(){printf("%i", i++);}
void D(){ x10( I ); }
void C(){ x10( D ); }
void M(){ x10( C ); }

int main(){
    M();
}


1
2
3
4
5
6
7
#include <iostream>
#include <iterator>
using namespace std;

int num() { static int i = 1; return i++; }
int main() { generate_n(ostream_iterator<int>(cout,"
"
), 1000, num); }

难看的C答案(每10次幂只展开一个堆栈帧):

1
2
3
4
5
6
7
8
9
10
#define f5(i) f(i);f(i+j);f(i+j*2);f(i+j*3);f(i+j*4)
void f10(void(*f)(int), int i, int j){f5(i);f5(i+j*5);}
void p1(int i){printf("%d,",i);}
#define px(x) void p##x##0(int i){f10(p##x, i, x);}
px(1); px(10); px(100);

void main()
{
  p1000(1);
}


堆栈溢出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>

static void print_line(int i)
{  
 printf("%d
"
, i);
 print_line(i+1);
}  

int main(int argc, char* argv[])
{  
 //get up near the stack limit
 char tmp[ 8388608 - 32 * 1000 - 196 * 32 ];
 print_line(1);
}

这是一个8MB的堆栈。每个函数调用似乎占用大约32个字节(因此32 * 1000)。但是当我运行它时,我只得到804(因此196 * 32;也许C运行时在堆栈中还有其他部分你必须扣除)。


功能指针的乐趣(不需要新的TMP):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>


#define MSB(typ) ((sizeof(typ) * CHAR_BIT) - 1)

void done(int x, int y);
void display(int x, int y);

void (*funcs[])(int,int)  = {
    done,
    display
};

void done(int x, int y)
{
    exit(0);
}

void display(int x, int limit)
{
    printf("%d
"
, x);
    funcs[(((unsigned int)(x-limit)) >> MSB(int)) & 1](x+1, limit);
}


int main()
{
    display(1, 1000);
    return 0;
}

作为旁注:我还禁止条件限制扩展到逻辑和关系运算符。如果允许逻辑否定,则递归调用可以简化为:

1
funcs[!!(limit-1)](x+1, limit-1);


我觉得这个答案非常简单易懂。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int print1000(int num=1)
{
    printf("%d
"
, 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;        
}


我错过了所有的乐趣,所有好的C ++答案都已经发布了!

这是我能想到的最奇怪的事情,我不会打赌这是合法的C99:p

1
2
3
4
5
6
7
8
#include <stdio.h>

int i = 1;
int main(int argc, char *argv[printf("%d
"
, i++)])
{
  return (i <= 1000) && main(argc, argv);
}

另一个,有点作弊:

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
#include <boost/preprocessor.hpp>

#define ECHO_COUNT(z, n, unused) n+1
#define FORMAT_STRING(z, n, unused)"%d
"

int main()
{
    printf(BOOST_PP_REPEAT(1000, FORMAT_STRING, ~), BOOST_PP_ENUM(LOOP_CNT, ECHO_COUNT, ~));
}

最后的想法,同样的欺骗:

1
2
3
4
5
6
7
8
9
#include <boost/preprocessor.hpp>
#include <iostream>

int main()
{
#define ECHO_COUNT(z, n, unused) BOOST_PP_STRINGIZE(BOOST_PP_INC(n))"
"
    std::cout << BOOST_PP_REPEAT(1000, ECHO_COUNT, ~) << std::endl;
}


非常简单:

1
2
3
4
int main(int argc, char* argv[])
{
    printf(argv[0]);
}

执行方法:

1
printer.exe"1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;20;21;22;23;24;25;26;27;28;29;30;31;32;33;34;35;36;37;38;39;40;41;42;43;44;45;46;47;48;49;50;51;52;53;54;55;56;57;58;59;60;61;62;63;64;65;66;67;68;69;70;71;72;73;74;75;76;77;78;79;80;81;82;83;84;85;86;87;88;89;90;91;92;93;94;95;96;97;98;99;100;101;102;103;104;105;106;107;108;109;110;111;112;113;114;115;116;117;118;119;120;121;122;123;124;125;126;127;128;129;130;131;132;133;134;135;136;137;138;139;140;141;142;143;144;145;146;147;148;149;150;151;152;153;154;155;156;157;158;159;160;161;162;163;164;165;166;167;168;169;170;171;172;173;174;175;176;177;178;179;180;181;182;183;184;185;186;187;188;189;190;191;192;193;194;195;196;197;198;199;200;201;202;203;204;205;206;207;208;209;210;211;212;213;214;215;216;217;218;219;220;221;222;223;224;225;226;227;228;229;230;231;232;233;234;235;236;237;238;239;240;241;242;243;244;245;246;247;248;249;250;251;252;253;254;255;256;257;258;259;260;261;262;263;264;265;266;267;268;269;270;271;272;273;274;275;276;277;278;279;280;281;282;283;284;285;286;287;288;289;290;291;292;293;294;295;296;297;298;299;300;301;302;303;304;305;306;307;308;309;310;311;312;313;314;315;316;317;318;319;320;321;322;323;324;325;326;327;328;329;330;331;332;333;334;335;336;337;338;339;340;341;342;343;344;345;346;347;348;349;350;351;352;353;354;355;356;357;358;359;360;361;362;363;364;365;366;367;368;369;370;371;372;373;374;375;376;377;378;379;380;381;382;383;384;385;386;387;388;389;390;391;392;393;394;395;396;397;398;399;400;401;402;403;404;405;406;407;408;409;410;411;412;413;414;415;416;417;418;419;420;421;422;423;424;425;426;427;428;429;430;431;432;433;434;435;436;437;438;439;440;441;442;443;444;445;446;447;448;449;450;451;452;453;454;455;456;457;458;459;460;461;462;463;464;465;466;467;468;469;470;471;472;473;474;475;476;477;478;479;480;481;482;483;484;485;486;487;488;489;490;491;492;493;494;495;496;497;498;499;500;501;502;503;504;505;506;507;508;509;510;511;512;513;514;515;516;517;518;519;520;521;522;523;524;525;526;527;528;529;530;531;532;533;534;535;536;537;538;539;540;541;542;543;544;545;546;547;548;549;550;551;552;553;554;555;556;557;558;559;560;561;562;563;564;565;566;567;568;569;570;571;572;573;574;575;576;577;578;579;580;581;582;583;584;585;586;587;588;589;590;591;592;593;594;595;596;597;598;599;600;601;602;603;604;605;606;607;608;609;610;611;612;613;614;615;616;617;618;619;620;621;622;623;624;625;626;627;628;629;630;631;632;633;634;635;636;637;638;639;640;641;642;643;644;645;646;647;648;649;650;651;652;653;654;655;656;657;658;659;660;661;662;663;664;665;666;667;668;669;670;671;672;673;674;675;676;677;678;679;680;681;682;683;684;685;686;687;688;689;690;691;692;693;694;695;696;697;698;699;700;701;702;703;704;705;706;707;708;709;710;711;712;713;714;715;716;717;718;719;720;721;722;723;724;725;726;727;728;729;730;731;732;733;734;735;736;737;738;739;740;741;742;743;744;745;746;747;748;749;750;751;752;753;754;755;756;757;758;759;760;761;762;763;764;765;766;767;768;769;770;771;772;773;774;775;776;777;778;779;780;781;782;783;784;785;786;787;788;789;790;791;792;793;794;795;796;797;798;799;800;801;802;803;804;805;806;807;808;809;810;811;812;813;814;815;816;817;818;819;820;821;822;823;824;825;826;827;828;829;830;831;832;833;834;835;836;837;838;839;840;841;842;843;844;845;846;847;848;849;850;851;852;853;854;855;856;857;858;859;860;861;862;863;864;865;866;867;868;869;870;871;872;873;874;875;876;877;878;879;880;881;882;883;884;885;886;887;888;889;890;891;892;893;894;895;896;897;898;899;900;901;902;903;904;905;906;907;908;909;910;911;912;913;914;915;916;917;918;919;920;921;922;923;924;925;926;927;928;929;930;931;932;933;934;935;936;937;938;939;940;941;942;943;944;945;946;947;948;949;950;951;952;953;954;955;956;957;958;959;960;961;962;963;964;965;966;967;968;969;970;971;972;973;974;975;976;977;978;979;980;981;982;983;984;985;986;987;988;989;990;991;992;993;994;995;996;997;998;999;1000"

规范并没有说必须在代码中生成序列:)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;

class Printer
{
public:
 Printer() { cout << ++i_ <<"
"
; }
private:
 static unsigned i_;
};

unsigned Printer::i_ = 0;

int main()
{
 Printer p[1000];
}


如果接受POSIX解决方案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/time.h>
#include <pthread.h>

static void die(int sig) {
    exit(0);
}

static void wakeup(int sig) {
    static int counter = 1;
    struct itimerval timer;
    float i = 1000 / (1000 - counter);

    printf("%d
"
, counter++);

    timer.it_interval.tv_sec = 0;
    timer.it_interval.tv_usec = 0;
    timer.it_value.tv_sec = 0;
    timer.it_value.tv_usec = i; /* Avoid code elimination */
    setitimer(ITIMER_REAL, &timer, 0);
}

int main() {
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    signal(SIGFPE, die);
    signal(SIGALRM, wakeup);
    wakeup(0);
    pthread_mutex_lock(&mutex);
    pthread_mutex_lock(&mutex); /* Deadlock, YAY! */
    return 0;
}

更多预处理程序滥用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>

#define A1(x,y) #x #y"0
" #x #y"1
" #x #y"2
" #x #y"3
" #x #y"4
" #x #y"5
" #x #y"6
" #x #y"7
" #x #y"8
" #x #y"9
"
#define A2(x) A1(x,1) A1(x,2) A1(x,3) A1(x,4) A1(x,5) A1(x,6) A1(x,7) A1(x,8) A1(x,9)
#define A3(x) A1(x,0) A2(x)
#define A4 A3(1) A3(2) A3(3) A3(4) A3(5) A3(6) A3(7) A3(8) A3(9)
#define A5"
1
2
3
4
5
6
7
8
9
" A2() A4"1000
"

int main(int argc, char *argv[]) {
    printf(A5);
    return 0;
}

我觉得很脏我想我现在会洗澡。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>

void nothing(int);
void next(int);
void (*dispatch[2])(int) = {next, nothing};

void nothing(int x) { }
void next(int x)
{
    printf("%i
"
, x);
    dispatch[x/1000](x+1);
}

int main()
{
    next(1);
    return 0;
}

由于对bug没有限制..

1
2
int i=1; int main() { int j=i/(i-1001); printf("%d
"
, i++); main(); }

甚至更好(?),

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdlib.h>
#include <signal.h>

int i=1;
int foo() { int j=i/(i-1001); printf("%d
"
, i++); foo(); }

int main()
{
        signal(SIGFPE, exit);
        foo();
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>

typedef void (*fp) (int);

void stop(int i)
{
   printf("
"
);
}

void next(int i);

fp options[2] = { next, stop };

void next(int i)
{
   printf("%d", i);
   options[i/1000](++i);
}

int main(void)
{
   next(1);
   return 0;
}


对于C ++爱好者

1
2
3
4
5
6
7
8
int main() {
  std::stringstream iss;
  iss << std::bitset<32>(0x12345678);
  std::copy(std::istream_iterator< std::bitset<4> >(iss),
            std::istream_iterator< std::bitset<4> >(),
            std::ostream_iterator< std::bitset<4> >(std::cout,"
"
));
}

使用指针算法,我们可以使用自动数组初始化为0。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>

void func();
typedef void (*fpa)();
fpa fparray[1002] = { 0 };

int x = 1;
void func() {
 printf("%i
"
, x++);
 ((long)fparray[x] + &func)();
}

void end() { return; }

int main() {
 fparray[1001] = (fpa)(&end - &func);
 func();
 return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
template <int To, int From = 1>
struct printer {
    static void print() {
        cout << From << endl;
        printer<To, From + 1>::print();
    }
};    

template <int Done>
struct printer<Done, Done> {
     static void print() {
          cout << Done << endl;
     }
};

int main()
{
     printer<1000>::print();
}


预处理器滥用!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>

void p(int x) { printf("%d
"
, x); }

#define P5(x) p(x); p(x+1); p(x+2); p(x+3); p(x+4);
#define P25(x) P5(x) P5(x+5) P5(x+10) P5(x+15) P5(x+20)
#define P125(x) P25(x) P25(x+50) P25(x+75) P25(x+100)
#define P500(x) P125(x) P125(x+125) P125(x+250) P125(x+375)

int main(void)
{
  P500(1) P500(501)
  return 0;
}

预处理程序(见gcc -E input.c)很有趣。


没有人说不应该事后发生段错,对吧?

注意:这在我的64位Mac OS X系统上可以正常工作。对于其他系统,您需要相应地将args更改为setrlimit和spacechew的大小。 ;-)

(我不需要包括这个,但为了以防万一:这显然不是一个良好的编程实践的例子。但它确实有利用它利用这个网站的名称。)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <sys/resource.h>
#include <stdio.h>

void recurse(int n)
{
    printf("%d
"
, n);
    recurse(n + 1);
}

int main()
{
    struct rlimit rlp;
    char spacechew[4200];

    getrlimit(RLIMIT_STACK, &rlp);
    rlp.rlim_cur = rlp.rlim_max = 40960;
    setrlimit(RLIMIT_STACK, &rlp);

    recurse(1);
    return 0; /* optimistically */
}

OpenMP版本(当然没有订购):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <omp.h>

int main(int argc, char** argv)
{
#pragma omp parallel num_threads(1000)
    {          
#pragma omp critical
        {
            std::cout << omp_get_thread_num() << std::endl;
        }
    }

    return 0;
}

(不适用于VS2010 OpenMP运行时(限制为64个线程),但在Linux上可以使用,例如,英特尔编译器)

这也是订购版本:

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
#include <omp.h>

int main(int argc, char *argv[])
{
  int i = 1;
  #pragma omp parallel num_threads(1000)
  #pragma omp critical
    printf("%d", i++);
  return 0;
}


这仅使用O(log N)堆栈并使用McCarthy评估http://en.wikipedia.org/wiki/Short-circuit_evaluation作为其递归条件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>

int printN(int n) {
  printf("%d
"
, 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);
}


我已经重新阐述了比尔提出的使其更具普遍性的伟大例程:

1
2
3
4
5
6
7
8
9
10
void printMe ()
{
    int i = 1;
    startPrintMe:
    printf ("%d
"
, i);
    void *labelPtr = &&startPrintMe + (&&exitPrintMe - &&startPrintMe) * (i++ / 1000);
    goto *labelPtr;
    exitPrintMe:
}

更新:第二种方法需要2个功能:

1
2
3
4
5
6
7
8
9
void exitMe(){}
void printMe ()
{
    static int i = 1; // or 1001
    i = i * !!(1001 - i) + !(1001 - i); // makes function reusable
    printf ("%d
"
, i);
    (typeof(void (*)())[]){printMe, exitMe} [!(1000-i++)](); // :)
}

对于这两种情况,您只需拨打电话即可启动打印

1
printMe();

已经过GCC 4.2测试。


从所谓的重复中接受的答案的C ++变体:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void print(vector<int> &v, int ind)
{
    v.at(ind);
    std::cout << ++ind << std::endl;
    try
    {
        print(v, ind);
    }
    catch(std::out_of_range &e)
    {
    }
}

int main()
{
    vector<int> v(1000);
    print(v, 0);
}


1
2
3
4
5
6
7
8
9
10
11
12
template <int remaining>
void print(int v) {
 printf("%d
"
, v);
 print<remaining-1>(v+1);
}

template <>
void print<0>(int v) {
}

print<1000>(1);


1
2
3
4
5
6
7
8
9
#include<stdio.h>
int b=1;
int printS(){    
    printf("%d
"
,b);
    b++;
    (1001-b) && printS();
}
int main(){printS();}


用宏!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<stdio.h>
#define x001(a) a
#define x002(a) x001(a);x001(a)
#define x004(a) x002(a);x002(a)
#define x008(a) x004(a);x004(a)
#define x010(a) x008(a);x008(a)
#define x020(a) x010(a);x010(a)
#define x040(a) x020(a);x020(a)
#define x080(a) x040(a);x040(a)
#define x100(a) x080(a);x080(a)
#define x200(a) x100(a);x100(a)
#define x3e8(a) x200(a);x100(a);x080(a);x040(a);x020(a);x008(a)
int main(int argc, char **argv)
{
  int i = 0;
  x3e8(printf("%d
"
, ++i));
  return 0;
}


也可以使用普通的动态调度(也可以在Java中工作):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#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 ++代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void print_number(uint number)
{
    try
    {
        print_number(number-1);
    }
    catch(int e) {}
    printf("%d", number+1);
}

void main()
{
    print_number(1001);
}

如何另一个异常终止示例。这次调整堆栈大小以在1000次递归时运行。

1
2
3
4
5
6
7
8
int main(int c, char **v)
{
    static cnt=0;
    char fill[12524];
    printf("%d
"
, cnt++);
    main(c,v);
}

在我的机器上它打印1到1000

1
2
3
4
5
6
7
995
996
997
998
999
1000
Segmentation fault (core dumped)


我对这一套精彩答案的贡献很小(它返回零):

1
2
3
4
5
6
7
#include <stdio.h>

int main(int a)
{
    return a ^ 1001 && printf("%d
"
, main(a+1)) , a-1;
}

逗号运营商是FTW o /


使用宏压缩:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>

#define a printf("%d",++i);
#define b a a a a a
#define c b b b b b
#define d c c c c c
#define e d d d d

int main ( void ) {
    int i = 0;
    e e
    return 0;
}

或者更好:

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>

#define a printf("%d",++i);
#define r(x) x x x x x
#define b r(r(r(a a a a)))

int main ( void ) {
    int i = 0;
    b b
    return 0;
}

manglesky的解决方案很棒,但没有足够的混淆。 :-)所以:

1
2
3
4
#include <stdio.h>
#define TEN(S) S S S S S S S S S S
int main() { int i = 1; TEN(TEN(TEN(printf("%d
"
, i++);))) return 0; }

受到Orion_G的回答和reddit讨论的启发;使用函数指针和二进制算术:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#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
"
,++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;
}

经过一些修修补补后,我想到了这个:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
template<int n>
class Printer
{
public:
    Printer()
    {        
        std::cout << (n + 1) << std::endl;
        mNextPrinter.reset(new NextPrinter);
    }

private:
    typedef Printer<n + 1> NextPrinter;
    std::auto_ptr<NextPrinter> mNextPrinter;
};

template<>
class Printer<1000>
{
};

int main()
{
    Printer<0> p;
    return 0;
}

后来@ ybungalobill的提交激发了我这个更简单的版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct NumberPrinter
{
    NumberPrinter()
    {
        static int fNumber = 1;
        std::cout << fNumber++ << std::endl;
    }
};


int main()
{
    NumberPrinter n[1000];
    return 0;
}


编辑2:

我从代码中删除了未定义的行为。感谢@sehe的通知。

没有循环,递归,条件和一切标准C ...(qsort滥用):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <stdlib.h>

int numbers[51] = {0};

int comp(const void * a, const void * b){
    numbers[0]++;
    printf("%i
"
, numbers[0]);
    return 0;
}

int main()
{
  qsort(numbers+1,50,sizeof(int),comp);
  comp(NULL, NULL);
  return 0;
}


c ++利用RAII

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;

static int i = 1;
struct a
{
    a(){cout<<i++<<endl;}
    ~a(){cout<<i++<<endl;}
}obj[500];

int main(){return 0;}

C利用宏

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>

#define c1000(x) c5(c5(c5(c4(c2(x)))))
#define c5(x) c4(x) c1(x) //or x x x x x
#define c4(x) c2(c2(x))   //or x x x x
#define c2(x) c1(x) c1(x) //or x x
#define c1(x) x

int main(int i){c1000(printf("%d
"
,i++);)return 0;}

编辑:还有一个,这个很简单

1
2
3
4
#include <stdio.h>
#define p10(x) x x x x x x x x x x
int main(int i){p10(p10(p10(printf("%d
"
,i++);)))return 0;}

C利用复发

编辑:此c代码包含<=和?:运算符

1
2
3
4
#include <stdio.h>

int main(int i){return (i<=1000)?main(printf("%d
"
,i++)*0 + i):0;}


循环和条件语句都没有,至少它不会在我的机器上崩溃:)。使用一些指针魔术我们有......

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <stdlib.h>
#include <stdio.h>

typedef void (*fp) (void *, int );

void end(fp* v, int i){
    printf("1000
"
);
    return;
}

void print(fp *v, int i)
{
    printf("%d
"
, 1000-i);
    v[i-1] = (fp)print;
    v[0] = (fp)end;
    (v[i-1])(v, i-1);

}

int main(int argc, char *argv[])
{
    fp v[1000];

    print(v, 1000);

    return 0;
}


你真的不需要基本的字符串处理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include

std::string r(std::string s, char a, char b)
{
    std::replace(s.begin(), s.end(), a, b);
    return s;
}

int main()
{
    std::string s0 =" abc
"
;
    std::string s1 = r(s0,'c','0')+r(s0,'c','1')+r(s0,'c','2')+r(s0,'c','3')+r(s0,'c','4')+r(s0,'c','5')+r(s0,'c','6')+r(s0,'c','7')+r(s0,'c','8')+r(s0,'c','9');
    std::string s2 = r(s1,'b','0')+r(s1,'b','1')+r(s1,'b','2')+r(s1,'b','3')+r(s1,'b','4')+r(s1,'b','5')+r(s1,'b','6')+r(s1,'b','7')+r(s1,'b','8')+r(s1,'b','9');
    std::string s3 = r(s2,'a','0')+r(s2,'a','1')+r(s2,'a','2')+r(s2,'a','3')+r(s2,'a','4')+r(s2,'a','5')+r(s2,'a','6')+r(s2,'a','7')+r(s2,'a','8')+r(s2,'a','9');
    std::cout << r(r(s1,'a',' '),'b',' ').substr(s0.size())
          << r(s2,'a',' ').substr(s0.size()*10)
          << s3.substr(s0.size()*100)
          <<"1000
"
;
}

那你觉得怎么样?

1
2
3
4
int main(void) {
    printf(" 1 2 3 4 5 6 7 8");
    return 0;
}

我打赌1000是二进制的
他显然正在检查那个人的CQ(compSci商数)


这是标准C:

1
2
3
4
5
6
7
8
9
#include <stdio.h>

int main(int argc, char **argv)
{
    printf("%d", argc);
    (void) (argc <= 1000 && main(argc+1, 0));

    return 0;
}

如果你不带参数调用它,它将打印从1到1000的数字。请注意,&&运算符不是"条件语句",即使它用于相同的目的。


我想知道面试官是否出现了一个不同的问题:在不使用循环的情况下计算从1到1000(或从任何n到m)的数字之和。它还教导了一个关于分析问题的好教训。在C中从1到1000打印#s将始终依赖于您可能不会在生产程序中使用的技巧(Main中的尾递归,计算真实性的副作用,或preproc和模板技巧)。

这将是一个很好的抽查,看你是否有任何类型的数学训练,因为关于高斯及其解决方案的古老故事可能会为任何进行过任何数学训练的人所熟知。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <stdlib.h>

void print(int n)
{
    int q;

    printf("%d
"
, n);
    q = 1000 / (1000 - n);
    print(n + 1);
}

int main(int argc, char *argv[])
{
    print(1);
    return EXIT_SUCCESS;
}

它最终会停止:P


不知道编写代码的C(++)是否足够,但您可以使用递归而不是循环。为了避免这种情况,您可以使用在第1000次访问后抛出异常的数据结构。例如。某种带范围检查的列表,您可以在每次递归时增加/减少索引。

从评论来看,C ++中似乎没有任何范围检查列表?

相反,你可以1 / n,其中n是递归函数的参数,每次调用时减少1。从1000开始.DivisionByZero Exception将停止递归


我讨厌打破它,但递归和循环在机器级别基本上是相同的。

不同之处在于使用JMP / JCC与CALL指令。两者具有大致相同的循环时间并刷新指令流水线。

我最喜欢的递归技巧是手动编写返回地址的PUSH并将JMP用于函数。然后该函数表现正常,并在结束时返回,但返回到其他地方。这对于更快地解析非常有用,因为它减少了指令管道刷新。

原始海报可能要么完全展开,模板人员要解决;如果您确切知道终端文本的存储位置,则将内存分页到终端中。后者需要很多洞察力并且风险很大,但几乎没有计算能力,而且代码没有像1000 printfs那样的肮脏。


将1到1000放在文件"文件"中

1
2
3
4
5
int main()
{
    system("cat file");
    return 0;
 }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
#include<stdexcept>

using namespace std;

int main(int arg)

{
    try

    {

        printf("%d
"
,arg);
        int j=1/(arg-1000);
        main(arg+1);
    }

    catch(...)
    {
        exit(1);
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
        #include <stdio.h>
        #include <stdlib.h>
        #include <string.h>

        typedef void(*word)(int);

        word words[1024];

        void print(int i) {
                printf("%d
"
, 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);
        }


到目前为止,由于堆栈溢出有很多异常退出,但还没有堆栈,所以这是我的贡献:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <cstdio>
#include <cstdlib>
#include <sys/mman.h>
#include <sys/signal.h>
#define PAGE_SIZE 4096
void print_and_set(int i, int* s)
{
  *s = i;
  printf("%d
"
, i);
  print_and_set(i + 1, s + 1);
}
void
sigsegv(int)
{
  fflush(stdout); exit(0);
}
int
main(int argc, char** argv)
{
  int* mem = reinterpret_cast<int*>
    (reinterpret_cast<char*>(mmap(NULL, PAGE_SIZE * 2, PROT_WRITE,
                                  MAP_PRIVATE | MAP_ANONYMOUS, 0, 0)) +
     PAGE_SIZE - 1000 * sizeof(int));
  mprotect(mem + 1000, PAGE_SIZE, PROT_NONE);
  signal(SIGSEGV, sigsegv);
  print_and_set(1, mem);
}

不是很好的练习,也没有错误检查(原因很明显),但我认为这不是问题的关键所在!

还有很多其他异常终止选项,当然,其中一些更简单:assert(),SIGFPE(我认为有人做过那个),依此类推。


令人惊讶的是,如果你放弃"必须使用C或C ++"的要求,它会变得多么容易:

Unix shell:

1
2
echo {1..1000} | tr ' ' '
'

要么

1
yes | nl | awk '{print $1}' | head -1000

如果您运行的是没有yes命令的Unix变体,请使用一些其他生成至少1000行的进程:

1
find / 2> /dev/null | nl | awk '{print $1}' | head -1000

要么

1
cat /dev/zero | uuencode - | nl | awk '{print $1}' | head -1000

要么

1
head -1000 /etc/termcap | nl -s: | cut -d: -f1


使用递归,可以使用函数指针算法替换条件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
#include <stdlib.h> // for: void exit(int CODE)

// function pointer
typedef void (*fptr)(int);

void next(int n)
{
        printf("%d
"
, 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!=0n==0是无分支操作。 (虽然,我们在尾调用中执行分支)。


我假设,由于这个问题的性质,不排除扩展?

另外,我很惊讶到目前为止没有人使用goto

1
2
3
4
5
6
7
8
9
10
11
int main () {
    int i = 0;
    void * addr[1001] = { [0 ... 999] = &&again};
    addr[1000] = &&end;
again:
    printf("%d
"
, i + 1);
    goto *addr[++i];
end:
    return 0;
}

好吧,从技术上讲它是一个循环 - 但它不再是一个循环,而不是到目前为止所有的递归示例;)


应该适用于任何不喜欢0/0的机器。如果需要,可以用空指针引用替换它。打印1到1000后程序可能会失败,对吧?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>

void print_1000(int i);
void print_1000(int i) {
    int j;
    printf("%d
"
, i);
    j = 1000 - i;
    j = j / j;
    i++;
    print_1000(i);
}

int main() {
    print_1000(1);
}


尽管这里看到了所有精彩的代码,但我认为唯一真正的答案是它无法完成。

为什么?简单。事实上,每一个答案都是循环的。隐藏为递归的循环仍在循环中。一看汇编代码就可以看出这个事实。即使用数字读取和打印文本文件也涉及循环。再看一下机器代码。键入1000个printf语句也意味着循环,因为printf本身内部有循环。

无法做到。


如果您的C编译器支持块,那么您可以编写以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>

void ten(void (^b)(void)) { b();b();b();b();b();b();b();b();b();b(); }

int main() {
    __block int i = 0;
    ten(^{
        ten(^{
            ten(^{
                printf("%d
"
, ++i);
            });
        });
    });
    return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;

template<int N>
void func()
{
        func<N-1>();
        cout << N <<"\t";
}

template<>
void func<1>()
{
        cout << 1 <<"\t";
}

int main()
{
        func<1000>();
        cout << endl;
        return 0;
}


1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>

int show(int i) {
   printf("%d
"
,i);
   return( (i>=1000) || show(i+1));
}


int main(int argc,char **argv) {
   return show(1);
}

||当i> = 1000时,运算符将递归调用短路显示。


假设程序以通常的方式运行(./a.out),以便它有一个参数,并忽略编译器类型警告,然后:

1
2
3
4
5
6
7
8
9
#include <stdio.h>
#include <stdlib.h>

void main(int i) {
    static void (*cont[2])(int) = { main, exit };
    printf("%d
"
, i);
    cont[i/1000](i+1);
}


我已经阅读了所有这些答案,而且我的所有答案都与众不同。 它是标准C并使用整数除法从数组中选择函数指针。 此外,它正确编译和执行,没有任何警告甚至通过"夹板"没有警告。

我当然受到了许多其他答案的启发。 即便如此,我的更好。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
#include <stdlib.h>

static int x(/*@unused@*/ const char * format, ...) { exit(0); }

static void p(int v, int e) {
    static int (*a[])(const char *, ...) = { printf, x };
    (void)a[v/(e+1)]("%d
"
, v);
    p(v+1, e);
}

int main(void) {
    p(1, 1000);
    return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
#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;
}

这是一个使用setjmp / longjmp的版本,因为有人必须这样做:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>

void print(int i) {
    printf("%d
"
, i);
}
typedef void (*func_t)(int);

int main() {
    jmp_buf buf;
    func_t f[] = {print, exit};
    int i = setjmp(buf)+1;
    f[i/1001](i);
    longjmp(buf, i);
    return 0;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
#include

void foo( int n )
{
 printf("%d
"
, n);
 assert( n > 0 );
 foo(--n);
}

int main()
{
 foo( 1000 );
 getchar();
}


1
2
3
4
5
6
#include <stdio.h>
int main(int argc, char** argv)
{
printf("numbers from 1 to 1000
"
);
}

1
2
3
4
5
6
7
8
9
10
11
#include <boost/mpl/range_c.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/lambda/lambda.hpp>
#include <iostream>

int main()
{
  boost::mpl::for_each<boost::mpl::range_c<unsigned, 1, 1001> >(std::cout << boost::lambda::_1 << '
'
);
  return(0);
}


这是我的2个解决方案。首先是C#,第二个是C:

C#:

1
2
3
4
5
6
7
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#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);
    index = sign(998-n)+1;
    actions[index](++n);
}

void main()
{
    actions[0] = &Action0;
    actions[1] = 0; //Not used
    actions[2] = &Action1;

    actions[2](0);
}

1
system("/usr/bin/env echo {1..1000}");


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    static void Main(string[] args)
    {
        print(1000);
        System.Console.ReadKey();
    }

    static bool print(int val)
    {
        try
        {
            print( ((val/val)*val) - 1);
            System.Console.WriteLine(val.ToString());
        }
        catch (Exception ex)
        {
            return false;
        }
        return true;
    }


这是使用信号的POSIX变体:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
#include <signal.h>

void counter(int done)
{
        static int i;

        done = ++i / 1000;

        printf("%d
"
, i);

        signal(SIGINT, (void (*)(int))(done * (int)SIG_DFL + (1-done) * (int)&counter));
        raise(SIGINT);
}

int main()
{
        signal(SIGINT, &counter);
        raise(SIGINT);

        return 0;
}

有趣的部分是counter()对signal()的调用。这里安装了一个新的信号处理程序:如果"done"为true则为SIG_DFL,否则为counter。

为了使这个解决方案更加荒谬,我使用信号处理程序的必需int参数来保存临时计算的结果。作为副作用,使用gcc -W -Wall编译时,恼人的"未使用变量"警告消失。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdio.h>

static void (*f[2])(int);
static void p(int i)
{
    printf("%d
"
, 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);
}


很难看出已经提出的所有解决方案,所以这可能是重复的。

我想用纯C而不是C ++来获得相对简单的东西。它使用递归,但与我看到的其他解决方案相反,它只进行对数深度的递归。通过表查找可以避免使用条件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
typedef void (*func)(unsigned, unsigned);
void printLeaf(unsigned, unsigned);
void printRecurse(unsigned, unsigned);


func call[2] = { printRecurse, printLeaf };

/* All array members that are not initialized
   explicitly are implicitly initialized to 0
   according to the standard. */

unsigned strat[1000] = { 0, 1 };


void printLeaf(unsigned start, unsigned len) {
  printf("%u
"
, start);
}

void printRecurse(unsigned start, unsigned len) {
  unsigned half0 = len / 2;
  unsigned half1 = len - half0;
  call[strat[half0]](start, half0);
  call[strat[half1]](start + half0, half1);
}

int main (int argc, char* argv[]) {
  printRecurse(0, 1000);
}

这甚至可以通过仅使用指针动态完成。相关变化:

1
2
3
4
5
6
7
unsigned* strat = 0;

int main (int argc, char* argv[]) {
  strat = calloc(N, sizeof(*strat));
  strat[1] = 1;
  printRecurse(0, N);
}

站在c ++概念,传递gcc,vc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[root@localhost ~]# cat 1.cpp
#include <stdio.h>
#include <stdlib.h>

int i = 1;
void print(int arg0)
{
    printf("%d",i);
    *(&arg0 - 1) = (int)print;
    *(&arg0 - i/1000) = (int)exit;
    i++;
}
int main(void) {
    int a[1000];
    print(0);
    return 0;
}

运行它:

1
2
3
4
[root@localhost ~]# g++ 1.cpp -o 1
[root@localhost ~]# ./1

1 2 ... 1000

因为它是答案:)

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


如果你不介意前导零,那么让我们跳过printf

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdlib.h>
void l();
void n();
void (*c[3])() = {l, n, exit};
char *a;
void (*x)();
char b[] ="0000";
void run() { x(); run(); }
#define C(d,s,i,j,f) void d() { s;x = c[i]; a = j;f; }
C(l, puts(b), 1+(a<b), b+3,)
C(n, int v = *a - '0' + 1; *a = v%10 + '0', v/10, a-1,)
C(main,,1,b+3, run())

为了好玩而投入的Javascript。包括1000自动停止:

1
2
3
4
5
6
7
8
9
10
var max = 1000;
var b = ["break"];
function increment(i) {
    var j = Math.abs(i - max);
    console.log(j);          
    b[(i/i) - 1].toString();
    i--;
    increment(i);    
}
increment(max);


注意:

  • 请期待获得结果。
  • 这个程序经常出错。

然后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <ctime>

#ifdef _WIN32
#include <windows.h>
#define sleep(x) Sleep(x*1000)
#endif

int main() {
  time_t c = time(NULL);
retry:
  sleep(1);
  std::cout << time(NULL)-c << std::endl;
goto retry;
}

显然需要Windows / Visual Studio ......但它确实有效。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <Windows.h>

void print(int x)
{
    int y;

    printf("%d
"
, x);
    __try
    {
        y = 1 / (x - 1000);
        print(x + 1);
    }
    __except(EXCEPTION_EXECUTE_HANDLER)
    {
        return;
    }
}

void main()
{
    print(1);
}

1
2
#include <stdio.h>
int main() { printf("numbers from 1 to 1000"); return 0; }

这就像关于英语单词的另一个谜语,以"gry"结尾,对吧?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

void (*f[2])(int v);

void p(int v)
{
  printf("%d
"
, v++);
  f[(int)(floor(pow(v, v - 1000)))](v);
}

void e(int v)
{
  printf("%d
"
, v);
}

int main(void)
{
  f[0] = p;
  f[1] = e;
  p(1);
}

一个脏代码:s

使用了xor和函数指针数组。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#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);
}

1
2
3
#include <stdio.h>
void main(int i){printf("%d
"
,i)&&i++<1000&&(*((int*)&i-1)-=5);}

另一个:

1
2
3
#include <stdio.h>
int main(int i){return i<=1000&&printf("%d
"
,i)&&main(++i);}

简单的C版本,终止于1000:

1
2
3
4
5
6
7
8
9
10
int print_stuff(int count) {
   printf("%d
"
, count);
   return (count ^ 1000) && print_stuff(count+1);
 }

 int main(int argc, char *argv[]) {
   print_stuff(1);
   return 0;
 }

如果你打算使用编译时递归,那么你可能还想使用除法和征服来避免达到模板深度限制:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

template<int L, int U>
struct range
{
    enum {H = (L + U) / 2};
    static inline void f ()
    {
        range<L, H>::f ();
        range<H+1, U>::f ();
    }
};

template<int L>
struct range<L, L>
{
    static inline void f ()
    {
        std::cout << L << '
'
;
    }
};

int main (int argc, char* argv[])
{
    range<1, 1000>::f ();
    return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <vector>

using namespace std;
#define N 10    //10 or 1000, doesn't matter

class A{
public:
    A(){
        //cout <<"A():" << m_ << endl;    //uncomment to show the difference between gcc and Microsoft C++ compiler
    }
    A(const A&){
        ++m_;
        cout << m_ << endl;    
    }
private:
    static int m_;  //global counter
};

int A::m_(0);  //initialization

int main(int argc, char* argv[])
{
    //Creates a vector with N elements. Printing is from the copy constructor,
    //which is called exactly N times.
    vector<A> v(N);  
    return 0;  
}

实施说明:
使用gcc:默认构造函数创建一个"master"元素。
然后由复制构造函数复制元素N次。
使用Microsoft C ++编译器:所有元素都是由默认构造函数创建的
然后由复制构造函数复制。


也许这太明显且易于理解,但这是标准的C ++,不会使用O(n)内存转储堆栈并在O(n)时间内运行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>

using namespace std;

int main (int argc, char** args) {
  vector<int> foo = vector<int>(1000);
  int terminator = 0;
 p:
  cout << terminator << endl;
  try {
    foo.at(terminator++);
  } catch(...) {
    return 0;
  }
  goto p;
}


我认为这些代码工作正常,易于理解,你可以打印任何像1到100或1到最终范围。 只需将其放入i并将其转移到呼叫功能。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{
    int i=1;
    call(i,i);
}

void call(int i,int j)
{
    printf("%d",i);
    sleep(1); // to see the numbers for delay
    j /= (j-1000);

    j = ++i;

    call(i,j);
}

因此,当j等于1000时,它除以零,它直接退出程序,这就是我打算输出数字的想法

或更简单的代码..

1
2
3
4
5
6
7
8
9
10
int main()
{
    static int i = 1;
    static int j = 1;
    printf("%d", i);
    sleep(1);
    j = ++i;
    j /= (j-1000);
    main();
}


您可以使用System()打印1到1000(使用DOS命令)

1
2
3
4
5
 include <process.h>
 void main()
 {
     system("cmd.exe /c for /l %x in (1, 1, 1000) do echo %x" );
 }

运行程序的.exe(可执行)文件,显示1到1000

注意:在WINDOWS中测试


我不认为这是一个"技巧问题"。 。 。"?:"不是有条件的,它是一个运营商。

那么使用递归和?:运算符来检测何时停止?

1
2
3
4
5
6
7
8
9
int recurse(i)
{
   printf("%d
"
, i);
   int unused = i-1000?recurse(i+1):0;

}

recurse(1);

或者沿着类似的变态思路。 。 。"&"条件中的第二个子句仅在第一个值为true时执行。所以递言如下:

1
i-1000 & recurse(i+1);

也许面试官认为表达而不是条件。


我不会写代码而只是想法。如何制作一个每秒打印一个数字的线程,然后另一个线程在1000秒后终止第一个线程?

注意:第一个线程通过递归生成数字。


递归?

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<stdio.h>
#define MAX 1000

int i = 0;
void foo(void) {
    if(i <= 1000) {
         printf("%d", i);
         i++;
    }
}
int main (void) {
    foo();
}


你可以使用递归。

像这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
void Print(int n)
{
  cout<<n<<"";  
  if(n>1000)
     return
  else
     return Print(n+1)
}    

int main ()
{
  Print(1);
}