Search code examples
javapalindromeperfect-square

java program that finds all palindrome perfect squares between two integers supplied as input


I need to write a program that finds all the palindrome perfect squares between two integers supplied as an input but that do not include the inputs supplied.

My program gets "killed" when you put in a large range of inputs i.e 10000 and 100000. How can i fix this please?

import static java.lang.Math.sqrt;
import java.util.Scanner;

public class PalinPerfect {

    public static void main(String[] args){

        Scanner user_input = new Scanner(System.in);
        String start_point;

        System.out.print("Enter start point N:\n");

        start_point = user_input.next();
        int start = Integer.parseInt(start_point);

        String finish_point;
        System.out.print("Enter ending point M:\n");

        finish_point = user_input.next();
        int finish = Integer.parseInt(finish_point);
        System.out.print( "The palindromic perfect squares are as follows:\n");

        for(int i=start; i <=finish; i++){

            int a,n1,n2=0;
            n1=i;

            for(a = 0; a <= i; a++) {

                if (a==Math.sqrt(n1)) {
                    n2=n1;
                }
            }
            int number = n2;
            int reversedNumber = 0;
            int temp=0;
            while(number > 0){
                temp = number % 10;
                number = number / 10;
                reversedNumber = reversedNumber * 10 + temp;
            }
                if(n1 == reversedNumber)
                    System.out.println(n1);

        }
    }
}

Solution

  • This is another simple and concise way to print palindrome square numbers.

    Make sure you check isPalindrome operation first then only you check isPerfectSquare.

    System.out.print("The palindromic perfect squares are as follows:\n");
    
            for (int i = start + 1; i < finish; i++) {
                if (isPalindrome(i) && isPerfectSquare(i) ) {
                    System.out.println(i);
                }
    
            }
    

    Define isPerfectSquare & isPalindrome methods as below

    static boolean isPerfectSquare(int input) {
        int SquareRoot = (int) Math.sqrt(input);
        return ((SquareRoot * SquareRoot) == input);
    }
    
    static boolean isPalindrome(int input) {
        String str = Integer.toString(input);
        return new StringBuffer(str).reverse().toString().equals(str);
    }