Please write the c-code below in matlab.

1 次查看(过去 30 天)
#include<stdio.h>
int main()
{
const int MAX = 1000;
char number[MAX+1];
int index;
int j;
for(index = 0; index <= MAX; index++)
{
number[index]=1;
}
for(index = 2; index
<= MAX; index++)
{
if(number[index]==1)
{
for(j=2*index; j<=MAX; j=j+index)
{ number[j]=0;
if(index%2==0)
number[j]=0;
else
if(index%3==0)
number[j]=0;
else
if(index%5==0)
number[j]=0;
else
if(index%7==0)
number[j]=0;
}
}
}
printf("The following numbers are prime:\n");
for(index=2;
index<=MAX; index++)
{
if(number[index]==1)
printf("%d\n",index);
}
return 0;
}
  1 个评论
Walter Roberson
Walter Roberson 2021-1-16
The code only checks factors 2, 3, 5, 7, and so produces incorrect answers for starting from 11^2 = 121.
A number of people have posted code to produce primes; why not use one of them?

请先登录,再进行评论。

回答(1 个)

Athul Prakash
Athul Prakash 2021-1-18
Hey Attcharapan,
I presume that you're trying to do somethign similar to the Sieve of Erastosthenes alrogithm and find prime numbers in the given range. You may check out the following File Exchange submission implementing the same:https://www.mathworks.com/matlabcentral/fileexchange/73941-erathostenes
Please note that File Exchange submissions are shared by the MATLAB user community and are not official Mathworks products (they are not written or tested by Mathworks itself).

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by