Skip to content

Instantly share code, notes, and snippets.

@SerpentChris
Last active January 19, 2017 23:02
Show Gist options
  • Save SerpentChris/e31759291d94959e587ad1a5af4960bc to your computer and use it in GitHub Desktop.
Save SerpentChris/e31759291d94959e587ad1a5af4960bc to your computer and use it in GitHub Desktop.
Prime sieve in C++ and Python
/*
Copyright (c) 2017 Chris Calderon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <iostream> // for cout, cin and endl
#include <cmath> // for sqrt
#include <cstdlib> //for atoi
#include <string> // for string
#include <fstream> // for writing output
#include <ctime> // for timing
#include <iomanip> // for printing time spent correctly
#define FROM_INDEX(x) 2*(x) + 3
#define TO_INDEX(x) ((x) - 3)/2
int main(int argc, const char * argv[]) {
if(argc < 2){
std::string full_name = std::string(argv[0]);
auto start = full_name.find_last_of('/');
std::string short_name = full_name.substr(start + 1);
std::cout << "Usage: " << short_name << " limit" << "[-p]" << std::endl;
return 1;
}
bool print = false;
std::string print_opt = std::string("-p");
if(argc > 2){
if(!print_opt.compare(argv[2]))
print=true;
}
int limit = std::atoi(argv[1]);
int primes_len = limit/2 - 1;
bool *primes = new bool[primes_len]();
int largest_num_to_check = TO_INDEX((int) sqrt(limit));
std::cout << "Finding all primes less than " << limit << std::endl;
auto start_time = time(NULL);
for(int i=0; i <= largest_num_to_check; i++){
if(!primes[i]){
int step = FROM_INDEX(i);
int start = TO_INDEX(step*step);
for(int j=start; j < primes_len; j+=step)
primes[j] = true;
}
}
std::cout.precision(10);
std::cout << "done in "<< std::scientific << difftime(time(NULL), start_time) << " seconds." << std::endl;
if(print){
bool first=true;
std::cout << '[';
for(int i=0; i < primes_len; i++){
if(!primes[i]){
if(first){
std::cout << FROM_INDEX(i);
first=false;
} else {
std::cout << ", " << FROM_INDEX(i);
}
}
}
std::cout << ']' << std::endl;
} else {
std::cout << "Writing results to primes.bin" << std::endl;
auto output = std::fstream("primes.bin", std::fstream::out|std::fstream::binary);
for(int i=0; i<primes_len; i++){
if(!primes[i]){
int temp = FROM_INDEX(i);
output.write(reinterpret_cast<const char*>(&temp), sizeof(int));
}
}
}
delete [] primes;
return 0;
}
#!/usr/bin/env python3
# Copyright (c) 2017 Chris Calderon
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import time
import sys
import os
def main():
if len(sys.argv) < 2:
shortname = os.path.basename(sys.argv[0])
print('Usage:', shortname, 'limit [-p]')
return 1
_print = False
if len(sys.argv) > 2:
if sys.argv[2] == '-p':
_print = True
limit = int(sys.argv[1])
primes_len = limit//2 - 1
primes = bytearray(primes_len)
largest_num_to_check = (int(limit**0.5) - 3)//2
print('Finding all primes less than', limit)
start_time = time.time()
for i in range(largest_num_to_check + 1):
if not primes[i]:
step = 2*i + 3
start = (step*step - 3)//2
for j in range(start, primes_len, step):
primes[j] = 1
print('done in %.10e' % (time.time() - start_time), 'seconds')
if _print:
first = True
print('[', sep='', end='', flush=True)
for i, e in enumerate(primes):
if not e:
if first:
print(2*i + 3, sep='', end='', flush=True)
first = False
else:
print(', ', 2*i + 3, sep='', end='', flush=True)
print(']')
else:
print('Writing results to primes2.bin')
output = open('primes2.bin', 'wb')
for i, e in enumerate(primes):
if not e:
output.write((2*i + 3).to_bytes(4, 'little'))
output.close()
return 0
if __name__ == '__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment