[英]Solution to go past the max value of integer?
您好親愛的社區,
我已經考慮了很長時間,但似乎找不到解決方案。
我有int[][] bino = new int[15][]
在其中計算帕斯卡金字塔的前15行,並且不允許更改類型(無double,long等)。
我們知道12位老師是479001600
int的最大值是2147483647,因此fac(12)仍然適合其中。
現在,對於最后三行,它變得很復雜。
Fac(13)是6227020800,對於int而言太大。
所以發生的是,對於第13,14和15行,它不會顯示正確的數字(因為6227020800 mod 2147483647 = 1932053506這意味着在我的示例中,fac(13)= 1932053506)。
問題是,是否有一種方法可以以某種方式仍然顯示正確的數字,而無需更改int[][] bino = new int[15][]
的字段類型int[][] bino = new int[15][]
)。 任何其他都可以更改。
public static void main(String args[])
{
int[][] bino = new int[15][]; //Create 2d array for pascal pyramid
for(int i = 0; i < bino.length;i++)
for(int j = 0; j < bino[i].length;j++)
{
binos[i][j] = nOverk(i,j)
}
}
public int nOverk(int n, int k)
{
return(fac(n) / (fac(k) * fac((n-k))));
}
public int fac(int z) //Calculats the faculty of a number
{
int res = 1;
if(z == 0 || z == 1)
return 1;
for(int i = 2; i <= z; i++)
res *= i;
return res;
}
AFAICT您只能使用resp。 需要fac()
用於nOverk()
。 在術語fac(n) / (fac(k) * fac((nk))))
您可以抵消一些因素,將臨時值保持在允許的范圍內。
例如,您只需計算(4 * 3) / (2 * 1)
代替nOverk(4,2) = 4*3*2*1 / ((2*1) * (2 * 1))
(4 * 3) / (2 * 1)
。 在某些極端情況下,這無濟於事,但我認為任務是通過這種方式定義的,以便有所幫助。
public int nOverk(int n, int k)
{
return (lim_fac(n, k) / lim_fac(k, k));
}
private int lim_fac(int z, int n) //Calculats the "limited" faculty of a number, by multiplying n factors.
{
int res = 1;
if (n == 0) {
return 1;
}
if (n == 1) {
return z;
}
for (int i = z - n + 1; i <= z; i++) {
res *= i;
}
return res;
}
注意:我不確定100%是否正確安裝了lim_fac()
,但您應該明白這一點。
簡單的解決方案是使用long
,但是您可以將int
用於更大的數字(並節省工作),而可以通過計算fac(a)/fac(b)
來提高效率。
public static void main(String... args) {
int[][] bino = new int[15][]; //Create 2d array for pascal pyramid
for (int i = 0; i < bino.length; i++) {
bino[i] = new int[i + 1];
for (int j = 0; j < i + 1; j++) {
bino[i][j] = nOverk(i, j);
}
}
}
static int nOverk(int n, int k) {
int min = Math.min(k, n - k);
int max = Math.max(k, n - k);
return fac(n, max) / fac(min, 1);
}
static int fac(int hi, int lo) {
if (hi == 0 || hi == 1)
return 1;
int res = 1;
for (int i = lo + 1; i <= hi; i++)
res *= i;
return res;
}
在Pascal三角形中,每個數字都是其正上方兩個數字的總和。 如果任務只是打印前15行,則不需要使用階乘。
public static void main(String[] args) {
int n = 15;
int[][] pascal = new int[n+1][];
// initialize first row
pascal[1] = new int[1+2];
pascal[1][1] = 1;
// fill in Pascal's triangle
for (int i = 2; i <= n; i++) {
pascal[i] = new int[i+2];
for (int j = 1; j < pascal[i].length - 1; j++)
pascal[i][j] = pascal[i-1][j-1] + pascal[i-1][j];
}
// print results
for (int i = 1; i <= n; i++) {
for (int j = 1; j < pascal[i].length - 1; j++) {
System.out.print(pascal[i][j] + " ");
}
System.out.println();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.