Improving order of operations and testing if a value has a decimal
Question: I'm trying to create a program that prints out pentagonal numbers up to n =
100. A pentagonal number is defined as n(3n-1)/2 for n = 1, 2, 3 so the first
pentagonal numbers would be 1, 5, 12, 22..etc

    
    
    package mathematical.functions.test;
    import java.util.Scanner;
    public class MathematicalFunctionsTest {
        public static int getPentagonalNumber(int n) {
            int i = 0;
            double part_one = (3 * n) - 1;
            double part_two = part_one / 2;
            while (i < 100){
                if (part_two == int(part_two))
                {
                    System.out.println(n);
                    i++;
                }
                else{                
            } 
        }
    }
    

This is just part of my program above. I have two problems right now:

  1. I do not know how to properly implement order of operations. What I have done is break up the operation n(3n - 1)/2 into part_one and part_two. Is this good practice?
  2. Looking at the nested if in the while loop, I am trying to test if part_two is an integer (i.e. has no decimal). I've tried many things but Java is not letting me. I tried using the % operator, too. But it did not let me aswell.

I've programmed in Python before and could do this easily there, but I think
right now I am struggling with the syntax mostly. I have to say however I was
at best a novice programmer in python, too (but I really enjoyed algorithms
there).

Thanks all...


Answer: You're missing part of your equation (factor of n). You can combine them into
one statement like so:

    
    
    double num = n * (3 * n - 1) / 2
    

Just use brackets the way you normally would. Java understands proper order of
operations.

Try the following to check if the number is an int:

    
    
    if ((num == Math.floor(num)) && !Double.isInfinite(num)) {
      // integral type
    }
    

This works by flooring (truncating the decimal) the number and checking to see
if it's the same as the original number. It also has the added check to ensure
that the number is finite.

