私はJavaにもっと慣れようとしているので、次の問題に対して独自のロジックを試してみてください最初の100個の正の整数に存在するすべての素数を出力してください...
import java.io.IOException;
class PrimeNumbers{
public static void main(String[] args) throws IOException
{
int[] num=new int[101]; //array to store values from 1 to 100
int[] prime=new int[50]; //array to store prime numbers
for(int i=1;i<=100;i++)
num[i]=i; //add values from 1 to 100 to "num" array
int i=1; //index for "num" array
int j=0; //index for "prime" array
int chk; //temporary variable to store value from "num" to carry out all "checking operations"
while(i<=100)
{
chk=num[i];
if(chk==1)
{
prime[j++]=chk;
i++;
break;
}
else if(chk==2)
{
i++;
break;
}
else if(chk==3)
{
prime[j++]=chk; //increment i and j after adding the "chk" value to "prime" array
i++;
break;
}
else if((chk % 2)!=0 && (chk % 3)!=0) //if number is divisible by 2 or 3,no need to check further
{
int k=4;
while(k<((chk+1)/2)) //check if value of "k" is less than half of "chk" value
{
if(chk%k!=0) k++; //increment "k" from 4 to half of chk's value and check if any of them is divisible
}
prime[j++]=chk;
i++;
break;
}
else
i++;
}
for(int n=0;n<prime.length;n++)
System.out.print(prime[n]+" "); //print the output
}
}
問題は、エラーが発生しないことですが、出力が期待したものではありません.3時間以上問題を解決しようとしましたが、うまくいきません..
助けていただければ幸いです、ありがとう!
出力 : 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
編集:同様のロジックで修正されたバージョン
import java.io.IOException;
class PrimeNumbers{
public static void main(String[] args) throws IOException
{
int[] prime=new int[50]; //array to store prime numbers
int i=1;
int j=0; //index for "prime" array
int chk; //temporary variable to store value i to carry out all "checking operations"
while(i<=100)
{
chk=i;
if(chk==1)
{
i++;
}
else if(chk==2)
{
prime[j++]=chk; //increment i and j after adding the "chk" value to "prime" array
i++;
}
else if(chk==3)
{
prime[j++]=chk; //increment i and j after adding the "chk" value to "prime" array
i++;
}
else if((chk % 2)!=0 && (chk % 3)!=0) //if number is divisible by 2 or 3,no need to check further
{
int k=5;
boolean flag=false;
while(k<(chk/2) && k<50) //check if value of "k" is less than half of "chk" value
{
if(chk%k!=0)
{
k++; //increment "k" from 4 to half of chk's value and check if any of them is divisible
}
else
{
flag=true;
break;
}
}
if(!flag)
{
prime[j++]=chk;
}
i++;
}
else
{
i++;
}
}
for(int n=0;n<prime.length;n++)
if(prime[n]!=0)
System.out.print(prime[n]+" "); //print the output
}
}
出力: 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