Greatest common divisor: Difference between revisions
Content added Content deleted
(Forth is usually case-insensitive) |
(Added Java examples.) |
||
Line 27: | Line 27: | ||
: gcd ( a b -- n ) |
: gcd ( a b -- n ) |
||
begin dup while tuck mod repeat drop ; |
begin dup while tuck mod repeat drop ; |
||
=={{header|Java}}== |
|||
===Iterative=== |
|||
public static long gcd(long a, long b){ |
|||
if(a == 0) return b; |
|||
if(b == 0) return a; |
|||
long retVal= 1; |
|||
long factor= 0; |
|||
factor= Math.max(a, b); |
|||
for(long loop= factor; loop > 1; loop--){ |
|||
if(a % loop == 0 && b % loop == 0){ |
|||
retVal= loop; |
|||
break; |
|||
} |
|||
} |
|||
return retVal; |
|||
} |
|||
===Recursive=== |
|||
public static long gcd(long a, long b){ |
|||
if(a == 0) return b; |
|||
if(b == 0) return a; |
|||
if(a > b) return gcd(b, a % b); |
|||
return gcd(a, b % a); |
|||
} |
Revision as of 14:29, 17 December 2007
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
This task requires the finding of the greatest common divisor of two integers.
ALGOL 68
PROC gcd = (INT a, b) INT: ( IF a = 0 THEN b ELIF b = 0 THEN a ELIF a > b THEN gcd(b, a MOD b) ELSE gcd(a, b MOD a) FI ); main : ( INT a = 33, b = 77; printf(($x"The gcd of"g" and "g" is "gl$,a,b,gcd(a,b))); INT c = 49865, d = 69811; printf(($x"The gcd of"g" and "g" is "gl$,c,d,gcd(c,d))) )
The output is:
The gcd of +33 and +77 is +11 The gcd of +49865 and +69811 is +9973
Forth
: gcd ( a b -- n ) begin dup while tuck mod repeat drop ;
Java
Iterative
public static long gcd(long a, long b){ if(a == 0) return b; if(b == 0) return a; long retVal= 1; long factor= 0; factor= Math.max(a, b); for(long loop= factor; loop > 1; loop--){ if(a % loop == 0 && b % loop == 0){ retVal= loop; break; } } return retVal; }
Recursive
public static long gcd(long a, long b){ if(a == 0) return b; if(b == 0) return a; if(a > b) return gcd(b, a % b); return gcd(a, b % a); }