Tuesday, September 1, 2009

Zend PHP 5 Certification Mock Exam: magic function

One of the Zend PHP 5 Certification Mock Exam questions shows recursive function called "magic". The question reads as follows (correct answer in bold):
What does the following function do, when passed two integer values for $p and $q?
<?php
function magic($p, $q) {
return ($q == 0)
? $p
: magic($q, $p % $q);
}
?>
  • Loops infinitely
  • Switches the values of $p and $q
  • Determines if they are both even or odd
  • Determines the greatest common divisor between them
  • Calculates the modulus between the two
It turns out that the function is simply on of the Euclidean algorithm implementations. If you do not remember from your math class how it works, here is the the Euclidean algorithm procedure described.

No comments:

Post a Comment