diff options
| author | Paulo Custodio <pauloscustodio@gmail.com> | 2023-04-09 12:28:28 +0100 |
|---|---|---|
| committer | Paulo Custodio <pauloscustodio@gmail.com> | 2023-04-09 12:28:28 +0100 |
| commit | 61db1a3bbc8c5a9cf2bccc6967a1e4b3ed7073be (patch) | |
| tree | a8995231e9f4e68465cfefc6f7f1b114ddfb1bcb /challenge-022 | |
| parent | 8a22d499e35f419b9f38b151d53fcf066b24d2ba (diff) | |
| download | perlweeklychallenge-club-61db1a3bbc8c5a9cf2bccc6967a1e4b3ed7073be.tar.gz perlweeklychallenge-club-61db1a3bbc8c5a9cf2bccc6967a1e4b3ed7073be.tar.bz2 perlweeklychallenge-club-61db1a3bbc8c5a9cf2bccc6967a1e4b3ed7073be.zip | |
Add C solution
Diffstat (limited to 'challenge-022')
| -rw-r--r-- | challenge-022/paulo-custodio/c/ch-1.c | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/challenge-022/paulo-custodio/c/ch-1.c b/challenge-022/paulo-custodio/c/ch-1.c new file mode 100644 index 0000000000..52c30201ba --- /dev/null +++ b/challenge-022/paulo-custodio/c/ch-1.c @@ -0,0 +1,54 @@ +/* +Challenge 022 + +Task #1 +Write a script to print first 10 Sexy Prime Pairs. Sexy primes are prime +numbers that differ from each other by 6. For example, the numbers 5 and 11 +are both sexy primes, because 11 - 5 = 6. The term "sexy prime" is a pun +stemming from the Latin word for six: sex. For more information, please +checkout wiki page. +*/ + +#include <stdio.h> +#include <stdlib.h> +#include <stdbool.h> + +bool is_prime(int n) { + if (n <= 1) + return false; + if (n <= 3) + return true; + if ((n % 2) == 0 || (n % 3) == 0) + return false; + for (int i = 5; i * i <= n; i += 6) + if ((n % i) == 0 || (n % (i + 2)) == 0) + return false; + return true; +} + +int next_prime(int n) { + if (n <= 1) + return 2; + do { + n++; + } while (!is_prime(n)); + return n; +} + +void print_sexy_primes(int count) { + int a = 1; + while (count > 0) { + a = next_prime(a); + int b = a; + while (b < a+6) + b = next_prime(b); + if (b == a+6) { + printf("(%d, %d)\n", a, b); + count--; + } + } +} + +int main() { + print_sexy_primes(10); +} |
