6

How do I amend what I have written to specify whether the user-input number is a perfect square?

I have tried placing various % placements, to no avail. The solutions I have found online don't use the M.O I desire.

I will include one solution I have found online, which I believe is ironically inefficient given the book's emphasis on avoiding brute force techniques, and doesn't seem to produce the desired results.

This problem is from Art And Science of Java Chapter 5, Programming Exercise number 7.

/** * This program tells the user whether the number they've entered returns a perfect square. * */ import acm.program.*; import java.lang.Math; public class Squares extends ConsoleProgram { public void run() { println("This program determines whether the number you're about to enter is a perfect square"); int s = readInt("Enter a positive number here: "); switch (s) { } if (isPerfectSquare(s)) { ; } { println((int) Math.sqrt(s)); } } private boolean isPerfectSquare(int m) { int sqrt = (int) Math.sqrt(m); return (sqrt * sqrt == m); } } 

And here's the solution I believe to be deficient:

/* * File: PerfectSquare.java * ------------------------- * This program test the isPerfectSquare(n) * that returns true if the integer n is a * perfect square. */ import acm.program.*; import java.lang.Math; public class Book extends ConsoleProgram { private static final int MIN_NUM = 1; private static final int MAX_NUM = 100000000; public void run() { int cnt = 0; for (int i = MIN_NUM; i <= MAX_NUM; i++) { if (isPerfectSquare(i)) { cnt++; println(cnt + ": " + (int) Math.sqrt(i) + ": " + i); } } } private boolean isPerfectSquare(int n) { int sqrt = (int) Math.sqrt(n); return (sqrt * sqrt == n); } } 
0

1 Answer 1

1

To know whether a given number has a perfect square-root you can try like given below -

if((Math.sqrt(m))%1 == 0) { System.out.println("Number (m) has a Perfect Square-Root"); } else { System.out.println("Number (m) does not have a Perfect Square-Root"); } 

As, if a number has a perfect square-root then number itself is a perfect-square.

It would help !

Sign up to request clarification or add additional context in comments.

6 Comments

if (m%10 is not one of (0, 1, 4, 5, 9)){ return false; } else return {Bruce's logic;}
@ElgsQianChen i think the logic i have given will be sufficient, won't it ?
Yes, it's just mod operation is much cheaper than square root operation. But frankly speaking, in most cases, if the code is not executed very frequently, I don't care about that. But if you are in a game programming, it may be well worth do this check.
okay, got your point !
@ElgsQianChen But what if m is 36 ? then according to your logic it will return false, although 36 is a perfect square.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.