Find first N pentagonal numbers

五迷三道 提交于 2019-12-07 09:34:00

问题


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 < )
    }
}

回答1:


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!

our signature looks like this:

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;
    }

}



回答2:


Notice that you are only executing the formula once and then incrementing it till you get 101. So you have essentionally done: 100 * (3 * 100 - 1) / 2 = 14950.

Consider having getPentagonalNumber return a single value and then call it x times with incrementing values starting at 1 until you get a value > 100 or until you have done it 100 times depending on your requirements.




回答3:


I think the way I'd structure this is to have getPentagonalNumber(int n) return the nth pentagonal number--just calculating one at a time. That keeps it easy to understand and to test. Worry about compiling a list of them in the main function which can call your getPentagonalNumber function.

You may want to have your main function store results into a List. When the list .size() == 10, call printResults(theResultList) (which you'll write using some of the code currently in main) and .clear() the list. Especially when starting out, keeping functions small and responsibilities clearly separated will help you keep track of what your code is doing.




回答4:


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



来源:https://stackoverflow.com/questions/7325410/find-first-n-pentagonal-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!