找出前N个五角形数 [英] Find first N pentagonal numbers
本文介绍了找出前N个五角形数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须找到1-100中的第一个N [pentagonal numbers][1]
,并每行显示10个.我也必须使用getPentagonalNumber(int n)
方法.显然这就是为什么它在那里.
I have to find the first N [pentagonal numbers][1]
from 1-100 and display them 10 per line. I have to use the getPentagonalNumber(int n)
method as well; that is obviously why it is there.
到目前为止,这是我的代码.
Here is my code so far.
package chapter_5;
public class Five_One {
public static void main(String[] args) {
int n = 0;
int numPerLine = 10;
for ( n = 0; n < 11; n ++)
}
public static int getPentagonalNumber(int n) {
int formula = n * (3 * n - 1) / 2;
while ( formula < )
}
}
推荐答案
这还有很长的路要走.让我们用更好的方法将其分解.
This has a long way to go. Let's break it down here with a better approach.
让我们创建一个返回一定数量的五边形数字的方法(我们将使用数组.)这使我们稍后在可能还有额外功劳的情况下也可以使用该方法!
Let's make a method that returns a set number of pentagonal numbers (we'll use an array.) This allows us to use the method later if perhaps there's extra credit too!
我们的签名如下:
class Jason {
public static void main(String[] args) {
// don't mix the calc routine and printing...
int[] pents = getPentagonals(100); // calcs and stores the first 100 values
final int numPerLine = 10;
for(int i = 0; i < pents.length; i++) {
System.out.print(pents[i]);
System.out.print(" ");
if(i % numPerLine == numPerLine - 1) System.out.println("");
}
}
static int[] getPentagonals(int n) {
int[] pents = new int[n];
// calculate pents
for(int i = 0; i < pents.length; i++) {
// calculate the ith pentagonal here (assuming the 0th is first)
// store it in pent[i]
}
return pents;
}
}
这篇关于找出前N个五角形数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文