求素数 matlab
时间: 2023-11-11 21:57:32 浏览: 69
要求求素数的 MATLAB 代码,可以使用以下方法:
```matlab
function primes = findPrimes(n)
primes = [];
for num = 2:n
isPrime = true;
for i = 2:sqrt(num)
if rem(num, i) == 0
isPrime = false;
break;
end
end
if isPrime
primes = [primes num];
end
end
end
```
这段代码定义了一个名为 `findPrimes` 的函数,它接受一个参数 `n`,然后返回小于等于 `n` 的所有素数。
相关问题
利用MATLAB求素数
以下是一种求素数的 MATLAB 代码:
```matlab
function primes = find_primes(n)
% This function finds all prime numbers less than or equal to n using
% the Sieve of Eratosthenes algorithm.
% Initialize an array of logical values indicating whether each number is prime
is_prime = true(1, n);
% Set the first two elements to false (0 and 1 are not prime)
is_prime(1:2) = false;
% Loop through the remaining numbers up to sqrt(n)
for ii = 2:sqrt(n)
% If the current number is prime
if is_prime(ii)
% Mark all multiples of the current number as not prime
is_prime(ii^2:ii:n) = false;
end
end
% Find all indices of the remaining true values in the is_prime array
primes = find(is_prime);
end
```
你可以调用这个函数来找到所有不大于给定数的素数。例如,要找到所有不大于100的素数,可以运行以下命令:
```matlab
primes = find_primes(100)
```
这将返回一个包含素数的向量 `[2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97]`。
matlab求10000以内素数
以下是 MATLAB 代码,可以求出 10000 以内的素数:
```matlab
% 求10000以内的素数
n = 10000;
prime = true(1, n);
prime(1) = false;
for i = 2:sqrt(n)
if prime(i)
for j = i^2:i:n
prime(j) = false;
end
end
end
% 输出素数
for i = 1:n
if prime(i)
fprintf('%d ', i);
end
end
```
这段代码先设置一个长度为 n 的布尔向量 prime,用于标记每个数是否为素数。然后从 2 到 sqrt(n) 依次枚举每个数,如果它是素数,则将它的倍数标记为非素数。最后输出所有被标记为素数的数。