Find first N pentagonal numbers

空扰寡人 提交于 2019-12-05 18:12:06

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

}

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.

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.

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

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