Skip to content

Instantly share code, notes, and snippets.

@trhgquan
Created October 15, 2019 06:14
Show Gist options
  • Save trhgquan/4f4b560ed10018bdfbb7dde042579111 to your computer and use it in GitHub Desktop.
Save trhgquan/4f4b560ed10018bdfbb7dde042579111 to your computer and use it in GitHub Desktop.
/*
* 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