[英]Java program to print exponential series for numbers 3 and 5 and limit the result to below 1000
我是Java編程新手,並且在Project Euler上嘗試了一些問題。 我以某種方式提出了我自己的指數3和5的打印順序問題,並將結果限制在1000以下。我進行了3天的研究,以找到解決此問題的最佳方法,但找不到相關文章。 我遇到過指數級的算法,但是對於我的能力而言,這些算法太先進了。
對於解決此問題的任何幫助,我將不勝感激。 請查看我嘗試過的代碼
public class Exponent {
public static void main (String[] args) {
// Declared integers for base and exponent
int i = 0; /* for base */
int n = 0; /* for exponent */
for (n=1; n<5; n++) {
for (i=1; i<=5; i++) {
if (i%3 == 0 || i%5 == 0) {
System.out.println(Math.pow(i,n));
}
}
}
}
}
此代碼輸出以下結果:
3.0
5.0
9.0
25.0
27.0
125.0
81.0
625.0
我的問題是,很明顯,我通過限制循環內的基數和指數值來強制將指數打印到1000以下
for (n=1; n<5; n++) //because n<=5 would print result for 5 power 5 which is 3125
我想以某種方式將結果限制為1000以下,所以不確定此聲明是否合適
int result = 1000; // result variable as 1000
另外,我希望代碼以3和5的交替打印輸出,如下所示。 我的程序分別按3和5的順序打印輸出。
Desired output:
3.0
5.0
9.0
27.0
125.0
81.0
625.0
243.0
729.0
並在那里停止,因為下一個值將超過1000。
我還想知道是否還有其他方法可以代替Math.pow()方法,因為它返回的是double而不是int。 我想避免使用double值,而只打印如下:
Without double:
3
5
9
27
81
125
243
625
729
不使用Math.pow()(並以不同順序打印):
int[] bases = { 3, 5 };
long maxval = 1000L;
for (int base : bases) {
long value = base;
do {
System.out.println( value );
value *= base;
} while (value < maxval);
}
為什么不檢查結果是否大於1000,如果結果超出范圍,就退出循環?
if(Math.pow(i,n)>=1000)
break;
暗示:
3.0 = 3^1
5.0 = 5^1
9.0 = 3^2
25.0 = 5^2 // I assume you forgot it
27.0 = 3^3
125.0 = 5^3
81.0 = 3^4
625.0 = 5^4
243.0 = 3^5
729.0 = 3^6
3 x始終小於5 x 。 因此,一個單循環(對於x部分)在循環體內具有兩個計算(一個為3,一個為5)應該可以完成這項工作。 您只需為少於1000個零件使用某種條件,以避免打印5 5和5 6 。
首先創建一個double來存儲結果:
double result = 0;
然后創建一個無限的while循環,使用3和5計算結果,並在結果超過1000時中斷。
while(true)
{
result = Math.pow(3, n);
if(result > 1000)
{
break;
}
System.out.println(((int)result));
result = Math.pow(5, n);
if(result < 1000)
{
System.out.println((int)result);
}
n++;
}
由於3的指數小於5,因此在達到3的最大指數之前不會爆發。 由於不會發生中斷,除非有效,否則請不要打印5。
也可以將double打印為int值,只需將其轉換為int即可。
編輯:
如果您真的擔心效率,這里是一個更快的解決方案:
public void calcExponents(int max)
{
int resultThree = 3;
int resultFive = 5;
while(resultThree < max)
{
System.out.println(resultThree);
if(resultFive < max)
{
System.out.println(resultFive);
}
resultThree *= 3;
resultFive *= 5;
}
}
您還可以設置3和5參數以使其更進一步。
您可以使用一個循環,在每次迭代中檢查3和5的指數,並打印每個小於1000的結果。
您只想確保3超過1000后就打破循環。
要打印整數值,只需將Math.pow()的結果強制轉換為int即可。
可以使用多種不同的方式編寫這樣的算法。 這是一個非常簡單(未經測試)的示例:
public class Exponent {
public static void main (String[] args) {
int i = 1; // or start at 0 if you prefer
// set the max value (could also be parsed from args)
int maxValue = 1000;
// the break condition also increments:
while (Math.pow(3, i++) < maxValue) {
int x3 = (int) Math.pow(3, i);
int x5 = (int) Math.pow(5, i);
if (x3 < maxValue) {
System.out.println(x3);
}
if (x5 < maxValue) {
System.out.println(x5);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.