简体   繁体   中英

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.

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 . 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:

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;
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM