大數階乘,大數階乘演算法

來源:互聯網
上載者:User

大數階乘,大數階乘演算法

轉載請註明出處:http://blog.csdn.net/ZhouLi_CSDN/article/details/46316855

很久沒寫演算法了,今天突然想寫一下大數階乘運算,花了一個多小時寫了一個demo,具體演算法時間空間複雜度最佳化並沒有考慮,有興趣可以自己研究一下。
什麼都不用說了附上代碼:

public class BigNumber {    public static void main(String[] args) {        //階乘因子        int jie = 8000;        int[] num1 = new int[5];        int[] num2 = new int[30000];        int[] result = new int[30000];        int length1 = num1.length;        int length2 = num2.length;        int length3 = result.length;        // int g = 0;        num1[0] = 1;        num2[0] = 1;        for (int i = 1; i < jie; i++) {            // 初始化num1  12345            num1[0] = i % 10;            num1[1] = (i / 10) % 10;            num1[2] = (i / 100) % 10;            num1[3] = (i / 1000) % 10;            num1[4] = (i / 10000) % 10;            //g表示進位            int g = 0;            for (int j = 0; j < length1; j++) {// num1                for (int m = 0; m < length2; m++) {// num2                    if ((m + j + 1) > 29999) {                        break;                    }                    int r = num1[j] * num2[m] + result[m + j] + g;                    g = 0;                    if (r > 9) {                        result[m + j] = r % 10;                        g = r / 10;                    } else {                        result[m + j] = r;                    }                }            }            //將一次計算結果進行轉換            for (int k = 0; k < length2; k++) {                num2[k] = 0;                num2[k] = result[k];                result[k] = 0;            }        }        //輸出結果        int flag = 0;        int fuck = 0;        for (int k = 29999; k >= 0; k--) {            if (num2[k] != 0) {                flag = 1;                fuck++;                System.out.print(num2[k]);            } else {                if (flag == 1) {                    fuck++;                    System.out.print(num2[k]);                }            }            if(fuck%60 == 0 && fuck != 0){                System.out.println("\n");            }        }        System.out.println("\n" + fuck + "");    }}

注釋寫的很清楚,可以嘗試運行檢驗結果:

檢驗網站:http://zh.numberempire.com/factorialcalculator.php

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.