之前有朋友在學資料結構時問到關於計算大數階層(Factorial)的問題,這問題其實也是很常見的程式題目,順便也來複習一下。
在普通情況下計算階層用個int變數來記運算結果就可以,但是當數字變大超出int範圍後就無法這樣做,這時可以改用陣列方式去記住每位數,所以假設是100大小的陣列就相當於100位數字,這樣就可以來處理大數的階層囉。因為這樣的作法相當於把每位數都拆開來看,所以每次在乘數字時,所有位數都必須要分別乘到,這點不同於普通情況是把整個結果直接拿去乘,想法上其實有點像傳統直式的乘法,而每次乘完後就必須要去處理進位的問題,保持每位數都是個位數0~9,最後計算完再從前面開始往後印就是答案了,參考程式如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace FactorialArray | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
int n = int.Parse(Console.ReadLine()); | |
int[] num = new int[n]; | |
int digit = 1; //位數 | |
num[0] = 1; | |
for (int i = 1; i <= n; i++) | |
{ | |
//所有位數都要乘 | |
for (int j = 0; j < n; j++) | |
num[j] *= i; | |
for (int k = 0; k < n - 1; k++) | |
{ | |
//超過個位數字時要進位 | |
if (num[k] > 9) | |
{ | |
num[k + 1] = num[k + 1] + num[k] / 10; | |
num[k] = num[k] % 10; | |
} | |
} | |
} | |
//查看有幾位數 | |
for (int i = n - 1; i >= 0; i--) | |
{ | |
if (num[i] != 0) | |
{ | |
digit = i + 1; | |
break; | |
} | |
} | |
//印出結果 | |
Console.Write(n + "!="); | |
for (int i = digit - 1; i >= 0; i--) | |
Console.Write(num[i]); | |
} | |
} | |
} |
0 意見:
張貼留言