Skip to content

Commit d5a6111

Browse files
authored
Merge pull request #8 from ubsan/master
add rust, haskell euclidean
2 parents ff4ab88 + f77cc03 commit d5a6111

File tree

1 file changed

+56
-2
lines changed
  • chapters/fundamental_algorithms/euclidean_algorithm

1 file changed

+56
-2
lines changed

chapters/fundamental_algorithms/euclidean_algorithm/euclidean.md

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,6 @@ The Euclidean Algorithm is truly fundamental to many other algorithms throughout
7474
*-----------------------------------------------------------------------------*/
7575

7676
#include <iostream>
77-
#include <math.h>
7877

7978
// Euclidean algorithm with mod
8079
int euclid_mod(int a, int b){
@@ -118,7 +117,6 @@ int main(){
118117
### C
119118
```c
120119
#include <stdio.h>
121-
#include <math.h>
122120
123121
int euclid_mod(int a, int b){
124122
@@ -277,3 +275,59 @@ namespace Euclidean_Algorithm
277275
}
278276
}
279277
```
278+
279+
### Haskell
280+
281+
```haskell
282+
euclidSub :: Integer -> Integer -> Integer
283+
euclidSub a b =
284+
if a == b then
285+
a
286+
else if a < b then
287+
euclidSub a (b - a)
288+
else
289+
euclidSub (a - b) b
290+
291+
euclidMod :: Integer -> Integer -> Integer
292+
euclidMod a 0 = a
293+
euclidMod a b = euclidMod b (a `mod` b)
294+
295+
main :: IO ()
296+
main = do
297+
let chk1 = euclidMod (64 * 67) (64 * 81)
298+
chk2 = euclidSub (128 * 12) (128 * 77)
299+
putStrLn (show chk1)
300+
putStrLn (show chk2)
301+
return ()
302+
```
303+
304+
### Rust
305+
306+
```rust
307+
fn euclid_sub(mut a: u64, mut b: u64) -> u64 {
308+
while a != b {
309+
if a < b {
310+
b = b - a;
311+
} else {
312+
a = a - b;
313+
}
314+
}
315+
a
316+
}
317+
318+
fn euclid_rem(mut a: u64, mut b: u64) -> u64 {
319+
while b != 0 {
320+
let tmp = b;
321+
b = a % b;
322+
a = tmp;
323+
}
324+
a
325+
}
326+
327+
fn main() {
328+
let chk1 = euclid_rem(64 * 67, 64 * 81);
329+
let chk2 = euclid_sub(128 * 12, 128 * 77);
330+
println!("{}", chk1);
331+
println!("{}", chk2);
332+
}
333+
```

0 commit comments

Comments
 (0)