Skip to content

Instantly share code, notes, and snippets.

@foota
Created May 14, 2012 18:07
Show Gist options
  • Select an option

  • Save foota/2695402 to your computer and use it in GitHub Desktop.

Select an option

Save foota/2695402 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
std::vector<int> primes;
for (int i = 3; i < 100; i += 2) primes.push_back(i);
auto end = primes.end();
for (auto x = primes.begin(); *x * *x <= *(end-1); ++x)
end = std::remove_if(x + 1, end, [&x](int p){ return p % *x == 0; });
primes.erase(end, primes.end());
for (auto p = primes.begin(); p != primes.end(); ++p) std::cout << *p << " ";
std::cout << std::endl;
primes = sieve [2..]
sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p /= 0]
primes = range(3, 100, 2)
for i in range(len(primes)):
if primes[i]**2 > primes[-1]: break
primes[i+1:] = filter(lambda p: p % primes[i] != 0, primes[i+1:])
print primes
"""
python -c "import sys;globals().__setitem__('P',range(3,100,2));[P.__setslice__(i+1,len(P),filter(lambda p:p%P[i]!=0,P[i+1:]))for i in range(len(P))if i<len(P)and P[i]**2<=P[-1]];[sys.stdout.write('%d '%p)for p in P]"
"""
@foota
Copy link
Copy Markdown
Author

foota commented May 14, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment