writing a method for an algorithm

Page 1 of 1

3 Replies - 4009 Views - Last Post: 03 October 2012 - 10:51 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=294113&amp;s=0a446cc3f96691150866b0499ed97942&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

#1 JazzyJessie

Reputation: 0
• 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

Reputation: 89
• 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?

#3 JazzyJessie

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

Re: writing a method for an algorithm

Posted 03 October 2012 - 09:59 AM

Kakerergodt, 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

#4 pbl

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

Reputation: 8365
• Posts: 31,956
• 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