TheAlgorithms-C/project_euler/problem_5/sol3.c

61 lines
1.3 KiB
C
Raw Normal View History

2020-06-05 19:20:25 +03:00
/**
* \file
* \brief [Problem 5](https://projecteuler.net/problem=5) solution (Fastest).
* @details Solution is the LCM of all numbers between 1 and 20.
*
* \see Slowest: problem_5/sol1.c
* \see Slower: problem_5/sol2.c
2020-06-05 19:20:25 +03:00
*/
2019-10-01 17:21:55 +03:00
#include <stdio.h>
2020-06-05 19:20:25 +03:00
/** Compute [Greatest Common Divisor
* (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of two numbers
* using Euclids algorithm
* @param a first number
* @param b second number
* @return GCD of `a` and `b`
2020-06-05 19:20:25 +03:00
*/
2020-04-08 16:41:12 +03:00
unsigned long gcd(unsigned long a, unsigned long b)
{
2019-10-01 17:21:55 +03:00
unsigned long r;
2020-04-08 16:41:12 +03:00
if (a > b)
{
2019-10-01 17:21:55 +03:00
unsigned long t = a;
a = b;
b = t;
}
2020-04-08 16:41:12 +03:00
while ((r = (a % b)))
{
2019-10-01 17:21:55 +03:00
a = b;
b = r;
}
return b;
}
2020-06-05 19:20:25 +03:00
/** Compute [Least Common Multiple
* (LCM)](https://en.wikipedia.org/wiki/Least_common_multiple) of two numbers
* @param a first number
* @param b second number
* @return LCM of `a` and `b`
2020-06-05 19:20:25 +03:00
*/
2020-04-08 16:41:12 +03:00
unsigned long lcm(unsigned long a, unsigned long b)
{
2019-10-01 17:21:55 +03:00
unsigned long long p = (unsigned long long)a * b;
return p / gcd(a, b);
}
/** Main function
* @returns 0 on exit
*/
2020-04-08 16:41:12 +03:00
int main(void)
{
2019-10-01 17:21:55 +03:00
unsigned long ans = 1;
unsigned long i;
2020-04-08 16:41:12 +03:00
for (i = 1; i <= 20; i++)
{
2019-10-01 17:21:55 +03:00
ans = lcm(ans, i);
}
printf("%lu\n", ans);
return 0;
}