Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
Loading...
Searching...
No Matches
sol3.c File Reference

Problem 5 solution (Fastest). More...

#include <stdio.h>
Include dependency graph for sol3.c:

Functions

unsigned long gcd (unsigned long a, unsigned long b)
 Compute Greatest Common Divisor (GCD) of two numbers using Euclids algorithm. More...
 
unsigned long lcm (unsigned long a, unsigned long b)
 Compute Least Common Multiple (LCM) of two numbers. More...
 
int main (void)
 Main function. More...
 

Detailed Description

Problem 5 solution (Fastest).

Solution is the LCM of all numbers between 1 and 20.

See also
Slowest: problem_5/sol1.c
Slower: problem_5/sol2.c

Function Documentation

◆ gcd()

unsigned long gcd ( unsigned long  a,
unsigned long  b 
)

Compute Greatest Common Divisor (GCD) of two numbers using Euclids algorithm.

Parameters
afirst number
bsecond number
Returns
GCD of a and b
19{
20 unsigned long r;
21 if (a > b)
22 {
23 unsigned long t = a;
24 a = b;
25 b = t;
26 }
27 while ((r = (a % b)))
28 {
29 a = b;
30 b = r;
31 }
32 return b;
33}

◆ lcm()

unsigned long lcm ( unsigned long  a,
unsigned long  b 
)

Compute Least Common Multiple (LCM) of two numbers.

Parameters
afirst number
bsecond number
Returns
LCM of a and b
42{
43 unsigned long long p = (unsigned long long)a * b;
44 return p / gcd(a, b);
45}
unsigned long gcd(unsigned long a, unsigned long b)
Compute Greatest Common Divisor (GCD) of two numbers using Euclids algorithm.
Definition: sol3.c:18
Here is the call graph for this function:

◆ main()

int main ( void  )

Main function.

Returns
0 on exit
51{
52 unsigned long ans = 1;
53 unsigned long i;
54 for (i = 1; i <= 20; i++)
55 {
56 ans = lcm(ans, i);
57 }
58 printf("%lu\n", ans);
59 return 0;
60}
unsigned long lcm(unsigned long a, unsigned long b)
Compute Least Common Multiple (LCM) of two numbers.
Definition: sol3.c:41
Here is the call graph for this function: