Last active
November 10, 2024 13:03
-
-
Save spamshaker/87d5256d3c3065939892f907b1b4b354 to your computer and use it in GitHub Desktop.
Counts primes in range and measures performance - TypeScript version and cpp version
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
#include <iostream> | |
#include <chrono> | |
#include <cmath> | |
bool isPrime(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 main() { | |
const int N = 100000; | |
int primes = 0; | |
auto start = std::chrono::high_resolution_clock::now(); | |
for (int i = 1; i < N; ++i) { | |
if (isPrime(i)) { | |
++primes; | |
} | |
} | |
auto end = std::chrono::high_resolution_clock::now(); | |
std::chrono::duration<double, std::milli> elapsed = end - start; | |
std::cout << "Primes: " << primes << "\n"; | |
std::cout << "Elapsed time: " << elapsed.count() << " milliseconds \n"; | |
return 0; | |
} | |
// Compilation | |
// > g++ -std=c++11 -O3 -o count-primes count-primes.cpp | |
// Running | |
// > ./count-prim |
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
function isPrime(n: number): number { | |
if (n === 1 || n === 0) return 0; | |
for (let i = 2; i <= n / 2; i++) { | |
if (n % i == 0) { | |
return 0; | |
} | |
} | |
return 1; | |
} | |
const start = performance.now(); | |
const N = 100000; | |
let primes = 0; | |
for (let i = 1; i < N; i++) | |
primes += isPrime(i); | |
const end = performance.now(); | |
const elapsed = end - start; | |
console.log(`Primes :${primes}\nElapsed time: ${elapsed} milliseconds`); | |
// Running | |
// `bun count-primes.ts` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment