[英]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.