Interesting short code snippets

Technical news items, notes & queries.
Post Reply
User avatar
Manna5
Posts: 14
Joined: 2021-Aug-03, 7:54 am
Contact:

Interesting short code snippets

Post by Manna5 »

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.
Pranav
Posts: 4
Joined: 2023-Nov-30, 9:14 am
Contact:

Re: Interesting short code snippets

Post by Pranav »

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.
Post Reply