-6

I want to write a java program to find the largest square number which is less than or equal to a given number.

For example when I insert 10 as the inputted number, the answer is 9 because 9is the largest square up to 10

I understand loops, but I can't figure out the logic behind this one.

Aurora0001
  • 13,139
  • 5
  • 50
  • 53
kago
  • 47
  • 8
  • 4
    Please read [the tour](http://stackoverflow.com/tour) and [*How do I ask a good question?*](http://stackoverflow.com/help/how-to-ask). – Biffen Jan 24 '17 at 10:44

3 Answers3

2

How about something like the following to get you going ...

double x = 20;
double root = Math.sqrt(x);
int t = (int)root;
System.out.println("Root is:" + root + " and answer is :" + t*t);
Stoat
  • 117
  • 9
0

Here is how to do this with loops

int n=10; //This is your Number
int i = 0;
for(i=n;i>=1;i--)
    if((int)Math.sqrt(i)*(int)Math.sqrt(i)==i)
        break;
System.out.println(i);

Below is how it works:-

The Loop runs from the n, which is your number, to 1. It then checks whether, the square root of i, which is running through n to 1, is a perfect square. If it is, it breaks the loop, and prints the value of i on the screen.

dumbPotato21
  • 5,669
  • 5
  • 21
  • 34
0
    public static void main(String argv[]){
        System.out.println(largestSquareLessOrEqualTo(145)); 
    } 

    public static int largestSquareLessOrEqualTo(int limit){
    int i = 0;
        for (; i <(int)Math.sqrt(limit); i++){
        }
        return(i*i);
    }
Eritrean
  • 15,851
  • 3
  • 22
  • 28