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);
}
}