一个for实现9*9乘法表

今天看到别人一个博客提出来一个非常有趣的题目,写一个9*9的乘法表,要求只使用且仅使用一个for来实现9*9乘法表的打印。(不使用if,switch,?:)
 
可以用任何语言实现,下面是博主给的java测试样例:
测试1:
public static void main(String[] args) {
new Test99().print(9);
}
运行结果:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81
测试2:
public static void main(String[] args) {
new Test99().print(5);
}
运行结果
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
 
既然只能用一个for,并且不能使用if,switch,?: 判断语句又需要打印出矩阵来,能想到就只有下面的逻辑了。
 
下面我用了两种方法来解决这个问题。
 
第一个方法是递归,第二个方法是逻辑运算,代码前面两个函数是普通的99表,和只用一个for不限制if的99表。
#include <stdio.h>

int _99;

void output(int n) {
    for(int i=1; i<=n; i++) {
        for(int j=1; j<=i; j++) {
            printf("%4d",i*j);
        }
        puts("");
    }
    return ;
}

void output_one_for(int n) {
    int i, j;
    for(i=1, j=1; j<=n; i++) {
        printf("%4d",i*j);
        if(j==i) {
            puts("");
            i=0;
            j++;
        }
    }
    return ;
}


bool output_one_for_zero_if(int n) {
    int i;
    for(i=1; i<=n; i++) {
        printf("%4d",i*n);
    }
    puts("");
    return n==_99 || output_one_for_zero_if(n+1);
}

void output_without_rec(int n){
    int i, j;
    for(i=1 ,j=1;j<=n;i++){
        printf("%4d",i*j);
        i%j||puts("");
        i%=j;
        i||j++;    
    }
}

void pt(int n) {
    _99 = n ;
    puts("normal 9*9 list:");
    output(_99);
    puts("
only for 9*9 list:");
    output_one_for(_99);
    puts("
only one for with out if,switch,?: 9*9 list:");
    output_one_for_zero_if(1);
    puts("
only one for and without recursive to make 9*9 list:");
    output_without_rec(_99);
    return ;
}

int main() {
    pt(9);
    return 0;
}
View Code

这个题目最难的地方莫过于换行, 昨天和【淦】日天交流这个题目的时候他也给出来另外一种换行的方法。 

void ZRT(int n){
    int i, j;
    for(i=1,j=1;j<=n;i++){
        printf("%4d",i*j);
        printf("%c","
"[i==j]);  //意思就是将"
"看作一个字符串的函数名,利用[i==j]来取输出''还是'
'。有趣的操作。
        i%=j;
        i||j++;
    }
    return ;
}
View Code
原文地址:https://www.cnblogs.com/HDMaxfun/p/9391454.html