[英]Java non-prime numbers
I want to print non-prime numbers in an interval and calculate the quantity of numbers. 我想在间隔中打印非素数并计算数量。 For example, between 3 and 10, the non-prime numbers are 4,6,8,9 for this interval.
例如,在3到10之间,此间隔的非素数为4,6,8,9。
I created an array and put the nonprime numbers into the array. 我创建了一个数组,并将非质数放入数组中。 I can print them on the screen but when I tried to reach every single element on the array
nonPrime[0]
and nonPrime[1]
seems 0
. 我可以在屏幕上打印它们,但是当我尝试到达数组
nonPrime[0]
和nonPrime[1]
上的每个元素时, nonPrime[0]
似乎都是0
。 Also I need enough dimension array because it doesn't help to calculate the quantity of non-prime numbers. 我还需要足够的维数数组,因为它无助于计算非素数的数量。
That's what I tried: 那就是我尝试过的:
public static void main (String[] args)
{
int x=10;//end of the interval
int y=2;//first of the interval
int[]nonPrime=new int[10];
for(int i=y+1;i<x;i++)
{
for(int j=2;j<x;j++)
{
if(i!=j)
{
if((i%j==0))
{
nonPrime[j]=i;
break;
}
}
}
}
}
You can use a ArrayList instead of an int array like this: 您可以像这样使用ArrayList而不是int数组:
import java.util.ArrayList;
public static void main (String[] args)
{
int x=10;//end of the interval
int y=2;//first of the interval
ArrayList<Integer> nonPrime = new ArrayList<Integer>();
for(int i=y+1;i<x;i++)
{
for(int j=2;j<i;j++)
{
if((i%j==0))
{
nonPrime.add(i);
break;
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.