简体   繁体   中英

Print arithmetic progression using prime number java

there. I just make a arithmetic progression using prime number, i have shown the prime number, but when i want to print the arithmetic progression, it print something else.

Here's what i want to display:

1 3 6 11 18

This is my current code:

for(int i=2;i<=20;i++){
boolean isPrime = true;

for(int j=2; j < 1; j++){
  if(i%j==0){
    isPrime = false;
    break;
  }
}
if(isPrime){
  for (int k=1; k<=10; k++){
    System.out.print(k + " ");
    k+=i;
  }
}

The display what's shown:

1 4 7 10 1 5 9 1 6 1 7 1 8 1 9 1 10 1 1 1 1 1 1 1 1 1 1 1 1 

Can someone help me with this? Thank you before

You need to make some changes in the algo, especially in the inner loop

int sum = 0;
for (int i = 1; i <= 20; i++) {
    boolean isPrime = true;

    for (int j = i-1; j > 1; j--) {
        if (i % j == 0) {
            isPrime = false;
            break;
        }
    }
    if (isPrime) {
        sum = sum + i;
        System.out.println(sum);
    }
}

for (int j = i-1; j > 1; j--) We are doing this because we want to see if the number is prime. You can improve this logic by starting setting j to sqrt(I).

I think the best way to figure out the problem is to create a method that will return the next prime number, and to store the current number (the one that will get displayed ) in a variable so that each time it is displayed it gets upddated by incrementing it by the next prime number as shown in the code below:

public static void main(String[] args){
            int currentNumber = 1 ;
            int currentPrime = 2 ;
            int limit = 20 ;
            while(currentNumber <= limit) {
                System.out.print(" " + currentNumber + " ");
                currentNumber += currentPrime;
                currentPrime = nextPrimeNumber(currentPrime);
                
            }
        }
        private static int nextPrimeNumber(int currentPrime) {
            while(true) {
                if(isPrimeNumber(++currentPrime)) return currentPrime;
            }
        }
        private static boolean isPrimeNumber(int number) {
            for(int i = 2 ; i <= (int) Math.sqrt(number) ; i++) {
                if(number % i == 0) return false;
            }
            return true;
            
        }

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