不使用数组解决杨辉三角

JavaEE期末有个测试,最后一题是说要最少内存占用的情况下生成杨辉三角.

想了一下,不用数组和Collections应该是最快的。然后就写出了这个代码,分析后面有空补一下。

Code [Java]

import java.util.Scanner;

public class Test {
    
    public static void main(String[] args){
        int line  = 0;
        Scanner scanner = new Scanner(System.in);
        line = scanner.nextInt();
        scanner.close();
        for( int i = 0 ; i <=  line ; i ++){
            for( int j = 0 ; j <= i ; j ++ ){
                System.out.print(c(i,j)+" ");
            }
            System.out.println();
        }
    }
    
    /**
     * Calculate (m!)/(n!*(m-n)!)
     * @param m The number of all factors
     * @param n The number of the factors in a group
     * @return result
     */
    private static long c(int m,int n){
        long mRes = 1;
        long nRes = 1;
        long mnRes = 1;
        for( long i = 1 ; i <= m ; i ++){
            mRes = mRes * i;
        }
        for( long i = 1 ; i <= n ; i ++){
            nRes = nRes * i;
        }
        for( long i = 1 ; i <= (m-n) ; i ++){
            mnRes = mnRes * i;
        }
        return mRes/(nRes*mnRes);
    }


}
标签: none
返回文章列表 文章二维码
本页链接的二维码
打赏二维码