Psychology 9040a: Scientific Computing with MATLAB

Testing Primes

Here is the script to run the tests, testPrimeSpeed.m

scicomp_wins = 0;
mathworks_wins = 0;
for i=1e4:1e6
    if (mod(i, 1e4)==0)
	fprintf("%d\n", i);
    end
    tic
    answer = isprime(i);
    mathworks = toc;
    tic
    answer = isprimeScicomp2018(i);
    scicomp = toc;
    if (scicomp < mathworks)
	scicomp_wins = scicomp_wins + 1;
    elseif (scicomp > mathworks)
	mathworks_wins = mathworks_wins + 1;
    end
end
fprintf("scicomp: %d, mathworks: %d\n", scicomp_wins, mathworks_wins);

Here is our prime number testing function, isprimeScicomp2018.m

function the_answer = isprimeScicomp2018(n_to_be_tested)

the_answer = true;
if (n_to_be_tested <=1 )
    the_answer = false;
elseif (n_to_be_tested == 2)
    the_answer = true;
elseif (mod(n_to_be_tested, 2) == 0)
    the_answer = false;
else
    for j = 2:floor(sqrt(n_to_be_tested))
	if (mod(n_to_be_tested, j) == 0)
	    the_answer = false;
	    break
	end
    end
end
end