Find the first N pentagonal numbers

I need to find the first N [pentagonal numbers][1] from 1-100 and display them at 10 per line. I have to use the getPentagonalNumber(int n) method; it is obvious why it is.

Here is my code.

 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 < ) } } 
+4
source share
4 answers

This is a long way. Let me break it here with a better approach.

Let's create a method that returns a given number of pentagonal numbers (we will use an array). This allows us to use the method later, if perhaps there is an additional loan!

our signature is as follows:

 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; } } 
+3
source

Note that you only execute the formula once, and then increase it to get 101. Thus, you are doing it right: 100 * (3 * 100 - 1) / 2 = 14950.

Suppose getPentagonalNumber returns a single value and then calls it x times with increasing values, starting at 1, until you get a value> 100 or until you do it 100 times depending on your requirements.

+1
source

I think I would like to structure this so that getPentagonalNumber(int n) n pentagonal number - just calculating one at a time. This makes it easy to understand and verify. Worry about compiling their list in the main function, which can call your getPentagonalNumber function.

You might want your main function storage results to be in a List . When the list is .size() == 10 , call printResults(theResultList) (which you will write using some code currently in main ) and .clear() list. Especially when you get started, small functions and clearly defined responsibilities will help you keep track of what your code is doing.

+1
source

Shouldn't it be a return formula; , not return n; , since I assume that you are trying to return the answer to your calculation?

0
source

All Articles