Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Slightly faster is_prime function #19

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Conversation

rrrlw
Copy link

@rrrlw rrrlw commented Jul 13, 2018

Checks (on average) mod every third integer below sqrt(n) instead of every second. Benchmark test showed that current is_prime function is very slightly faster for faster test cases (about half the integers below 10,000) and the suggested is_prime function is faster (1-2.5x) for slower test cases. Benchmark code below.

#include <iostream>
#include <fstream>
#include <ctime>

using namespace std;

//ripser
bool is_prime1(const int16_t n)
{
	if (!(n & 1) || n < 2) return n == 2;

	for (int16_t p = 3, q = n / p, r = n % p; p <= q; p += 2, q = n / p, r = n % p)
		if (!r) return false;

	return true;
}

//checking only mod 6k+1, 6k-1
bool is_prime2(const int16_t n)
{
	if (!(n & 1) || n < 2)
		return (n == 2);

	if (n == 3)
		return true;
	else if (n % 3 == 0)
		return false;

	int16_t curr;
	for (int16_t i = 1; ; i++)
	{
		curr = 6 * i;
		if ((curr-1) * (curr-1) > n) break;
		if (n % (curr + 1) == 0 ||
			n % (curr - 1) == 0)
			return false;
	}
	return true;
}

int main()
{
	clock_t start, end;
	double duration;

	const int LEN = 10000,	//should be multiple of 10 for progress update to work properly
			NUM_RUNS = 25000;
	double time1[LEN];
	double time2[LEN];
	int progress = 0;

	for (int16_t currNum = 0; currNum < LEN; currNum++)
	{
		if (is_prime1(currNum) != is_prime2(currNum))
		{
			cout << "ERROR AT " << currNum << endl;
			return 1;
		}

		//record time for first prime method
		start = clock();

		for (int i = 0; i < NUM_RUNS; i++)
			is_prime1(currNum);

		end = clock();
		time1[currNum] = (end - start) / ((double) CLOCKS_PER_SEC);

		//record time for second prime method
		start = clock();

		for (int i = 0; i < NUM_RUNS; i++)
			is_prime2(currNum);

		end = clock();
		time2[currNum] = (end - start) / ((double) CLOCKS_PER_SEC);

		//update status
		if (currNum % (LEN / 10) == 0)
		{
			cout << progress << "% DONE" << endl;
			progress += 10;
		}
	}

	//update status
	cout << "DONE WITH TIMING" << endl;

	//output data to CSV
	ofstream fout("Times.csv");
	fout << "Method1,Method2\n";
	for (int i = 0; i < LEN; i++)
		fout << time1[i] << ',' << time2[i] << '\n';
	fout.close();

	//update status and exit
	cout << "DONE WITH DATA OUTPUT; PROGRAM TERMINATING." << endl;
	return 0;
}```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant