Page 1 of 1

Interesting short code snippets

Posted: 2023-May-15, 1:54 pm
I have a cool piece of C code to share with, you. This function does find the greatest common dividor using the well-known variant of Euclidean algorithm with division. The interesting thing is how it can be written using C while statement, conditional and assignment operators.

Code: Select all

``````int gcd (int a, int b) {
while ((a > b) ? (a %= b) : (b %= a));
return a | b;
}
``````
You can also share your interesting snippets of code, including one-liners, in this thread.

Re: Interesting short code snippets

Posted: 2023-Nov-30, 9:18 am
Manna5 wrote: 2023-May-15, 1:54 pm I have a cool piece of C code to share with, you. This function does find the greatest common dividor using the well-known variant of Euclidean algorithm with division. The interesting thing is how it can be written using C while statement, conditional and assignment operators.

Code: Select all

``````int gcd (int a, int b) {
while ((a > b) ? (a %= b) : (b %= a));
return a | b;
}
``````
You can also share your interesting snippets of code, including one-liners, in this thread.
This method highlights the beauty of succinct C syntax by using the well-known form of the Euclidean algorithm with division. To discover the largest common divisor, the while statement, conditional, and assignment operators work in unison.