/**
* This problem comes from
*   D. Cooper and M. Clancy.  Oh! Pascal! W.W. Norton & Co.: New York, 1985.  2nd ed.
*
* Problem 7-15 (p. 254)  The integer 36 has a peculiar property--it is a perfect square,
*   and is also the sum of the integers from 1 through 8.  The next such number is 1225,
*   which is 35^2 as well as the sum of 1 through 49.  Find the next number that is a
*   perfect square, and is also the sum of the series 1, ..., N.
*
* @author (Michael Branicky)
* 09/19-20/2006
*/

public class Peculiar {
  // Finds and prints next peculiar number > 1225
  public static void main(String args[]) {
    int curLargest = 1225;
    // int curLargest = 36;
    System.out.println("After "+curLargest+" next peculiar number is "+findNextPeculiar(curLargest));
  }

  // Finds and returns next peculiar number > bound
  public static int findNextPeculiar (int bound) {
    int i = bound + 1;
    while (!isPeculiar(i)) {
      i = i + 1; 
    }
    return i;
  }

  // Returns true if a number is peculiar; returns false if it isn't
  public static boolean isPeculiar (int a) {
     return (isPerfectSquare(a) && isSumFrom1toN(a));
  }

  // Returns true if a number is a perfect square; returns false if it isn't
  public static boolean isPerfectSquare (int a) {
    int r = 0;
    while (r*r<a) {
      r = r + 1;
    }
    if (r*r == a) { return true; } else { return false;}
  }

  // Returns true if a number is a sum of integers from 1 to N; false, if it isn't
  public static boolean isSumFrom1toN (int a) {
    int sum = 0;
    int i = 1;
    while (sum<a) {
      sum = sum + i;
      i = i + 1;
    }
    if (sum == a) { return true; } else { return false;}
  }
}
