From 4194b204f64aef8655bbfa7567bd7ef6ea3197ca Mon Sep 17 00:00:00 2001 From: Ajay Singh Date: Sat, 7 Dec 2019 13:03:23 +0530 Subject: [PATCH] Prime (#585) * Prime Here we can check prime upto 10^8 in O(1). It is very useful in Competitive programming. * Update and rename Math/Primeupto10^8.cpp to math/primes_up_to_10^8.cpp * long long -> int64 * cstdint::int64_t * int64_t * std::cin --- math/primes_up_to_10^8.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 math/primes_up_to_10^8.cpp diff --git a/math/primes_up_to_10^8.cpp b/math/primes_up_to_10^8.cpp new file mode 100644 index 000000000..db9b56cab --- /dev/null +++ b/math/primes_up_to_10^8.cpp @@ -0,0 +1,27 @@ +#include +#include + +char prime[100000000]; + +void Sieve(int64_t n) { + memset(prime, '1', sizeof(prime)); // intitize '1' to every index + prime[0] = '0'; // 0 is not prime + prime[1] = '0'; // 1 is not prime + for (int p = 2; p * p <= n; p++) { + if (prime[p] == '1') { + for (int i = p * p; i <= n; i += p) + prime[i] = '0'; // set all multiples of p to false + } + } +} + + +int main() { + Sieve(100000000); + int64_t n; + std::cin >> n; // 10006187 + if (prime[n] == '1') + std::cout << "YES\n"; + else + std::cout << "NO\n"; +}