-
-
Couldn't load subscription status.
- Fork 359
euclidean algorithm in crystal #887
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| def euclid_mod(a : Int, b : Int) | ||
| a = a.abs | ||
| b = b.abs | ||
|
|
||
| loop do | ||
| b, a = a % b, b | ||
| break if b == 0 | ||
| end | ||
|
|
||
| return a | ||
| end | ||
|
|
||
| def euclid_sub(a : Int, b : Int) | ||
| a = a.abs | ||
| b = b.abs | ||
|
|
||
| loop do | ||
| if a > b | ||
| a -= b | ||
| else | ||
| b -= a | ||
| end | ||
| break if a == b | ||
| end | ||
|
Comment on lines
+17
to
+24
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This goes into an infinite loop if a is equal to b. Moving the break to happen before the while a != b
if a > b
a -= b
else
b -= a
end
end |
||
|
|
||
| return a | ||
| end | ||
|
|
||
| def main | ||
| euc_mod = euclid_mod(64 * 67, 64 * 81) | ||
| euc_sub = euclid_sub(128 * 12, 128 * 77) | ||
|
|
||
| puts "Modulus-based euclidean algorithm result: #{euc_mod}" | ||
| puts "Subtraction-based euclidean algorithm result: #{euc_sub}" | ||
| end | ||
|
|
||
| main | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If b is already zero trying to do
a % bthrowsDivisionByZeroError. This could be fixed by breaking before this line, or usingwhileinstead ofloop