10.12.2012 Views

Prime Numbers

Prime Numbers

Prime Numbers

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

546 Appendix BOOK PSEUDOCODE<br />

Functions and return/report values<br />

Typically a customized function in our pseudocode is cast in the form<br />

func(x) {<br />

...;<br />

...;<br />

return y;<br />

}<br />

and the idea is the same as in most any modern language: One calls func(x)<br />

in the same way one would call a trigonometric function or a square root,<br />

with the attained value y. Similarly, a procedure (as opposed to a function)<br />

has the same syntax, with no returned value, although certain variables are<br />

usually set within a procedure. Also, a return statement is an exit statement,<br />

e.g., a sequence<br />

if(x = y) return x 3 ;<br />

return x 4 ;<br />

does not need an “else” structure for the x 4 case, because we always assume<br />

the current function/procedure exits immediately on any demand by the if()<br />

statement here. Likewise, a return statement, when executed, immediately<br />

causes exit from within any while() or for() loop.<br />

Finally, we use report statements in the following way. Instead of returning<br />

a value from a function/procedure, a report statement simply relays the<br />

value—as in printing it, or reporting it to another program—on the fly, as<br />

it were. Thus the following function exemplifies the use of report/return (the<br />

function assumes a subroutine that evaluates the number-of-divisors function<br />

d(n)):<br />

mycustomπ(x) { //Report (and count!) all primes not exceeding x.<br />

c =0; //This c will be the primes count.<br />

for(2 ≤ n ≤ x) {<br />

if(d(n) ==2) {<br />

c = c +1;<br />

report n; //As in “print” n, but keep looping.<br />

}<br />

}<br />

return c;<br />

}<br />

<strong>Prime</strong>s will be reported in ascending order, with the return value of function<br />

mycustomπ(x) being the classical π(x).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!