java Finding the nth Perfect Square

Hello everyone, I'm going to be showing you how to find the nth perfect square. A perfect square is a number who has a whole number square root. Example: √1 = 1, because 1 * 1 = 1. √4 = 2, because 2 * 2 = 4. √9 = 3, √16 = 4, √25 = 5, I'm sure all of you know this, just a quick reminder. These are the perfect squares: 1, 4, 9, 16, 25, 36, 49, 64... and it goes on forever. There is a pattern between each one though: the numbers are incremented by every odd number:
1 (+ 3) = 4 (+ 5) = 9 (+ 7) = 16 (+ 9) 25 (+ 11) = 36 (+ 13) = 49, etc.

This algorithm can easily be duplicated in a computer program, and the way the numbers are incremented just screams for a for loop:



private static void perfSquare(int n) {
for (int numb = 1, odd = 3, i = 1; i <= n; numb += odd, odd += 2, i++) {
System.out.println("Perfect Square #" + i + ": " + numb);
}
}

Explanation of code:
By initializing the variable odd at 3 and adding 2 every iteration, the loop processes through every odd number (3, 5, 7, 9...) and then adds the value stored in odd to numb every iteration as well. The variable i is used to keep track of the amount of iterations.

Output:
Perfect Square #1: 1
Perfect Square #2: 4
Perfect Square #3: 9
Perfect Square #4: 16
Perfect Square #5: 25
Perfect Square #6: 36
Perfect Square #7: 49
Perfect Square #8: 64
Perfect Square #9: 81
Perfect Square #10: 100

This algorithm can be used to find any perfect square.

Enjoy! 

Read more: http://forum.codecall.

net/topic/72218-finding-the-nth-perfect-square/#ixzz2GdmpkwpP

No comments:

Post a Comment