Created
October 15, 2019 06:14
-
-
Save trhgquan/4f4b560ed10018bdfbb7dde042579111 to your computer and use it in GitHub Desktop.
full source code with sample input: https://github.com/trhgquan/CPP/blob/master/sth_else/MISC/NEARPRIME.c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* https://github.com/trhgquan | |
*/ | |
#include <stdio.h> | |
int PRIME[2000004]; | |
void generatePrimes() { | |
for (int i = 2; i <= 2000004; ++i) | |
PRIME[i] = 1; | |
for (int i = 2; i <= 2000004; ++i) | |
for (int j = 2; j * i <= 2000004; ++j) | |
PRIME[i * j] = 0; | |
} | |
int nearestPrime(int n) { | |
// Special case: | |
if (n == 1) return 2; | |
generatePrimes(); | |
int a, b; | |
for (int i = n; i >= 2; --i) | |
if (PRIME[i]) { a = i; break; } | |
for (int i = n; i <= 2000004; ++i) | |
if (PRIME[i]) { b = i; break; } | |
if (n - a > b - n) return b; | |
return a; | |
} | |
int main() { | |
int n; | |
scanf("%d", &n); | |
printf("%d\n", nearestPrime(n)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment