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);
}
}
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 !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With