java - Given a number N, can N be expressed as the sum of two or more consecutive perfect squares? -


at recent computer programming competition at, there problem have determine if number n, 1<=n<=1000, palindromic square. palindromic square number can read same forwards , backwards , can expressed sum of 2 or more consecutive perfect squares. example, 595 palindrome , can expressed 6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2.

i understand how determine if number palindrome, i'm having trouble trying figure out if can expressed sum of 2 or more consecutive squares.

here algorithm tried:

public static boolean issumofsquares(int num) {           int sum = 0;           int lowerbound = 1;             //largest square root less num           int upperbound = (int)math.floor(math.sqrt(num));                       while(lowerbound != upperbound) {               for(int x=lowerbound; x<upperbound; x++) {                   sum += x*x;               }                              if(sum != num) {                   lowerbound++;               }               else {                   return true;               }               sum=0;                                                             }                      return false;       }

my approach sets upper boundary closest square root number , sets lower bound 1 , keeps evaluating sum of squares lower bound upper bound. issue lower bound changes while upper bound stays same.

this should efficient algorithm determining if it's sum of squares of consecutive numbers.

  1. start lower bound , upper bound of 1. current sum of squares 1.

    public static boolean issumofsquares(int num) {     int sum = 1;     int lowerbound = 1;     int upperbound = 1; 
  2. the maximum possible upper bound maximum number square less or equal number test.

    int max = (int) math.floor(math.sqrt(num)); 
  3. while loop. if sum of squares little, add next square, incrementing upperbound. if sum of squares high, subtract first square, incrementing lowerbound. exit if number found. if can't expressed sum of squares of consecutive numbers, upperbound exceed max, , false returned.

    while(sum != num) {      if (sum < num)      {          upperbound++;          sum += upperbound * upperbound;      }      else if (sum > num)      {          sum -= lowerbound * lowerbound;          lowerbound++;      }      if (upperbound > max)          return false; }  return true; 

tests 5, 11, 13, 54, 181, , 595. yes, of them aren't palindromes, i'm testing sum of squares of consecutive numbers part.

1: true 2: false 3: false 4: true 5: true 11: false 13: true 54: true 180: false 181: true 595: true 596: false 

Popular posts from this blog