1000! 超出 long 範圍,必須使用 System.Numerics.BigInteger。題目要求 C# 方法供 JavaScript 呼叫並綁定 Label,典型架構為 ASP.NET WebForm / WebAPI + 前端 AJAX。
using System;
using System.Numerics;
public class MathUtil
{
public static BigInteger Factorial(int n)
{
if (n < 0) throw new ArgumentException("n must be non-negative");
BigInteger result = 1;
for (int i = 2; i <= n; i++) result *= i;
return result;
}
}
[HttpGet]
[Route("api/math/factorial/{n}")]
public IHttpActionResult GetFactorial(int n)
{
try {
var result = MathUtil.Factorial(n);
return Ok(result.ToString()); // 傳回字串避免 JSON 序列化截斷
} catch (Exception ex) {
return BadRequest(ex.Message);
}
}
async function loadFactorial() {
try {
const resp = await fetch('/api/math/factorial/1000');
if (!resp.ok) throw new Error('Server error');
const bigNumStr = await resp.text();
document.getElementById('lblResult').innerText = bigNumStr;
} catch (e) {
console.error(e);
document.getElementById('lblResult').innerText = '計算失敗';
}
}
loadFactorial();
// Code-behind
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
lblResult.Text = MathUtil.Factorial(1000).ToString();
}
}
效能提示:1000! 約 2568 位數,BigInteger 乘法極快(毫秒級),無需快取。