Please write the c-code below in matlab.

조회 수: 2 (최근 30일)
Attcharapan Chailert
Attcharapan Chailert 2021년 1월 16일
답변: Athul Prakash 2021년 1월 18일
#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에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by