我正在尝试更熟悉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 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