This PHP programme returns the greatest common denominator from the input.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | /******************************************************* * MYCPLUS Sample Code - https://www.mycplus.com * * * * This code is made available as a service to our * * visitors and is provided strictly for the * * purpose of illustration. * * * * Please direct all inquiries to saqib at mycplus.com * *******************************************************/ <html> <head> <title>func_get_args</title> </head> <body> <? /* ** Function gcd ** Input: any number of integers ** Output: integer ** Description: Returns the greatest common ** denominator from the input. */ function gcd() { /* ** start with the smallest value and try every ** value until we get to 1, which is common to all */ $start = 2147483647; foreach(func_get_args() as $arg) { if(abs($arg) < $start) { $start = abs($arg); } } for($i=$start; $i > 1; $i--) { //assume we will find a gcd $isCommon = TRUE; //try each number in the supplied arguments foreach(func_get_args() as $arg) { //if $arg divided by $i produces a //remainder, then we don't have a gcd if(($arg % $i) != 0) { $isCommon = FALSE; } } //if we made it through the previous code //and $isCommon is still TRUE, then we found //our gcd if($isCommon) { break; } } return($i); } //prints 5 print(gcd(10, 20, -35) . "<br />\n"); ?> </body> </html> |