3 Replies - 1293 Views - Last Post: 03 October 2012 - 10:51 AM Rate Topic: -----

#1 JazzyJessie  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 03-October 12

writing a method for an algorithm

Posted 03 October 2012 - 09:25 AM

The method evenSquares takes a single int parameter, n, (for example, 10000), and then prints all of the (positive) even perfect squares less than n, each on a separate line. Notice that evenSquares has a void return type, since all it does is print integers to the console. Be sure to use the println method to print each entry of your output.

Example: if n = 40, your code should print

4
16
36

(Hint: your method should be built around a for loop with a test component that asks if the square of the control variable (say, k) is < n. Thus, the loop should terminate as soon as k*k equals or exceeds n.)

Is This A Good Question/Topic? 0
  • +

Replies To: writing a method for an algorithm

#2 Kakerergodt  Icon User is offline

  • D.I.C Head

Reputation: 87
  • View blog
  • Posts: 201
  • Joined: 01-May 12

Re: writing a method for an algorithm

Posted 03 October 2012 - 09:33 AM

Seems simple enough, have you given it a try? Anything specific you need help with?
Was This Post Helpful? 0
  • +
  • -

#3 JazzyJessie  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 03-October 12

Re: writing a method for an algorithm

Posted 03 October 2012 - 09:59 AM

View PostKakerergodt, on 03 October 2012 - 09:33 AM, said:

Seems simple enough, have you given it a try? Anything specific you need help with?


i got this:


public void evenSquares(int n){
for(k = 2; Math.sqrt(k) <= n; k = k + 2){
System.out.println(Math.sqrt(k));
}
}

but it doesn't work
Was This Post Helpful? 0
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: writing a method for an algorithm

Posted 03 October 2012 - 10:51 AM

System.out.println(Math.sqrt(k));

will print the square root of all the k specified
you want the exact square root and you want the input parameter to be even
I would rather go the other way:
- take all numbers
- raise them to of 2
- break out of the loop if you execeed the limits
- found if the result is even
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1