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

Problem 5 solution - Naive algorithm (Improved over problem_5/sol1.c) More...

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

Functions

static int check_number (unsigned long long n)
 Checks if a given number is devisable by every number between 1 and 20.
 
int main (void)
 Main function.
 

Variables

static unsigned int divisors []
 Hack to store divisors between 1 & 20.
 

Detailed Description

Problem 5 solution - Naive algorithm (Improved over problem_5/sol1.c)

Little bit improved version of the naive problem_5/sol1.c. Since the number has to be divisable by 20, we can start at 20 and go in 20 steps. Also we don't have to check against any number, since most of them are implied by other divisions (i.e. if a number is divisable by 20, it's also divisable by 2, 5, and 10). This all gives a 97% perfomance increase on my machine (9.562 vs 0.257)

See also
Slower: problem_5/sol1.c
Faster: problem_5/sol3.c

Function Documentation

◆ check_number()

static int check_number ( unsigned long long  n)
static

Checks if a given number is devisable by every number between 1 and 20.

Parameters
nnumber to check
Returns
0 if not divisible
1 if divisible
31{
32 for (size_t i = 0; i < 7; ++i)
33 {
34 if (n % divisors[i] != 0)
35 {
36 return 0;
37 }
38 }
39
40 return 1;
41}
static unsigned int divisors[]
Hack to store divisors between 1 & 20.
Definition sol2.c:21

◆ main()

int main ( void  )

Main function.

Returns
0 on exit
49{
50 for (unsigned long long n = 20;; n += 20)
51 {
52 if (check_number(n))
53 {
54 printf("Result: %llu\n", n);
55 break;
56 }
57 }
58 return 0;
59}
static int check_number(unsigned long long n)
Checks if a given number is devisable by every number between 1 and 20.
Definition sol2.c:30
Here is the call graph for this function:

Variable Documentation

◆ divisors

unsigned int divisors[]
static
Initial value:
= {
11, 13, 14, 16, 17, 18, 19, 20,
}

Hack to store divisors between 1 & 20.