joe doe
joe doe

Reputation: 13

MATLAB - How do I find the first integer of an infinite set that satisfies this condition?

I want to find the smallest integer P, such that the number of primes in the set {1,2,..., P} is less than P/6.

I think have the answer via (long) trial and error but would like to know how to verify this through MATLAB.

Upvotes: 1

Views: 85

Answers (1)

Suever
Suever

Reputation: 65460

You can use isprime to check if any value in an array is a prime number. If we want to check all integers up until the integer N we can do

% You can change this to the maximum number that you'd like to consider for P
N = 2000;

possible_P_values = 2:N;                % We omit 1 here since it's not a prime number
primes = isprime(possible_P_values);

To determine how many primes have occured up to a given integer N we can use cumsum of this logical matrix (the cumulative sum)

nPrimes_less_than_or_equal_to_P = cumsum(primes);

Then we can divide possible_P_values by 6 and check where the number of primes up to a certain point is less than that number.

is_less_than_P_over_6 = nPrimes_less_than_or_equal_to_P < (possible_P_values ./ 6);

Then we can identify the first occurance with find

possible_P_values(find(is_less_than_P_over_6, 1, 'first'))
%   1081

Upvotes: 2

Related Questions