whats wrong with this code? Im trying to find the first 50 primes in a sequence, and then sort it into a 5x10 array

2 次查看(过去 30 天)
function result = primenumbers(n)
if n <= 1
result = false;
return;
end
for i = 2:sqrt(n)
if rem(n, i) == 0
result = false;
return;
end
end
result = true;
end
primes = [];
n = 2;
while length(primes) < 50
if primenumbers(n)
primes = [primes n];
end
n = n + 1;
end

回答(1 个)

Dyuman Joshi
Dyuman Joshi 2023-5-11
Firstly, do not use built-in functions as variables names, primes in this case.
Secondly, all the functions in a script must be at the end. Shift any functions in the script to the bottom.
Use reshape to change the vector into a 5x10 array.
p = [];
n = 2;
while length(p) < 50
if primenumbers(n)
p = [p n];
end
n = n + 1;
end
p
p = 1×50
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 101 103 107 109 113
function result = primenumbers(n)
if n <= 1
result = false;
return;
end
for i = 2:sqrt(n)
if rem(n, i) == 0
result = false;
return;
end
end
result = true;
end
  2 个评论
Image Analyst
Image Analyst 2023-5-19
If this Answer solves your original question, then could you please click the "Accept this answer" link to award the answerer with "reputation points" for their efforts in helping you? They'd appreciate it. Thanks in advance. 🙂 Note: you can only accept one answer (so pick the best one) but you can click the "Vote" icon for as many Answers as you want. Voting for an answer will also award reputation points.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by