Home > Software design >  how can i check if the number is perfect square by not using math.sqrt
how can i check if the number is perfect square by not using math.sqrt

Time:10-28

i want to make a program which related to this question:

An integer that can be expressed as the square of another integer is called a perfect square, such as 4,9,16,25, etc. Write a progran that checks if a number is a perfect square.

I did built something goes like:

import java.util.Scanner;
class Q3{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int num = 0;
        int a = 0;
        System.out.println("Type a number to check if it has square");
        num = sc.nextInt();

        for(a = 1;a<num;a  ){ }

        if (a*a == num){
            System.out.println("Ok");
            break;
        }
        else if (a*a != num){
            System.out.println("Not ok");
        }
   }
}

So it doesn’t give what i want when i run it. What should i change or add ?

CodePudding user response:

I think your for loop interpretation might be wrong, I made up something that might just work. Give this code a try.. You can make the method return a boolean too if you want.

static void perfectSquare(int number) {
    for (int i = 1; i < i * number;   i) {
        // 'i' is the divisor, making sure
        // it is equal to the quotient
        if ((number % i == 0) && (number / i == i)) {
            System.out.println(i);
        }
    }

CodePudding user response:

If you want to brute force every number then you are on the right track but you should only print "Not ok" if all numbers in the loop have failed otherwise you may have a perfect square but "Ok" will be hidden within many "Not ok" lines. Also there is nothing in your for loop so the if statement always checks if 0*0 == num.

This looks like it may be a homework question so I won't give a full answer for you but think about how you can make this more efficient.

If you have found an integer number that matches do you need to keep going?

Do you need to check every number? (a starting point may be following the principles of a binary search)

CodePudding user response:

I ended up like this:

    import java.util.Scanner;
class Q3{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int num = 0;
        int a = 0;
        int b = 0;
        System.out.println("Type a number to check if it has square");
        num = sc.nextInt();

        for(a = 1;a<num;a  ){

             if (a*a == num){
                b = 1;
                break;
            
            }
            
      }

      if(b==1){
        System.out.println("Perfect Square");


      }
      else {
        System.out.println("Not ok");
      }

    }
}

Thanks for support !

  •  Tags:  
  • java
  • Related