Last active
December 19, 2024 20:12
-
-
Save mudassaralichouhan/178bfd172f6745a53b4543275645d11e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
bool isEven(int n) { | |
return (n & 1) == 0; | |
} |
This file contains hidden or 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
/* | |
* Sieve of Eratosthenes: An efficient algorithm to find all prime numbers up to a given limit. | |
* Time complexity: O(n log(log n)) | |
* Space complexity: O(n) | |
*/ | |
#include <iostream> | |
#include <vector> | |
#include <cstdlib> | |
std::vector<bool> sieveOfEratosthenes(int n) { | |
std::vector<bool> primes(n + 1, true); | |
primes[0] = primes[1] = false; | |
for (int i = 2; i * i <= n; i++) { | |
if (primes[i]) { | |
for (int j = i * i; j <= n; j += i) { | |
primes[j] = false; | |
} | |
} | |
} | |
return primes; | |
} | |
bool isPrime(int number) { | |
if (number <= 1) return false; | |
for (int i = 2; i * i <= number; i++) { | |
if (number % i == 0) return false; | |
} | |
return true; | |
} | |
int main() { | |
{ | |
int n = 100, i = 1, count = 0; | |
std::vector<bool> primes = sieveOfEratosthenes(n); | |
for (int i = 2; i <= primes.size(); i++) { | |
if (primes[i]) { | |
std::cout << i << ' '; | |
} | |
} | |
} | |
std::cout << std::endl; | |
{ | |
int n = 100, count = 0, number = 2; | |
while (count < n) { | |
if (isPrime(number)) { | |
std::cout << number << " "; | |
count++; | |
} | |
number++; | |
} | |
} | |
std::cout << std::endl; | |
return EXIT_SUCCESS; | |
} |
This file contains hidden or 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
void swap(int &a, int &b) { | |
a ^= b; | |
b ^= a; | |
a ^= b; | |
} |
Author
mudassaralichouhan
commented
Dec 19, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment