Home > database >  print prime numbers between 2 and n
print prime numbers between 2 and n

Time:10-12

I need to find all prime numbers between 2 and n, the user informs n. However, I cannot use "for", only "while", but I can't make the program works using "while". Can somebody help me? This is the program I made with "for"

import java.util.Scanner;
class Main {
    public static void main(String [] args) {
        int i;
        int cont;
        int n;
        System.out.print("Enter a number: ");
        Scanner leia = new Scanner(System.in);
        n = leia.nextInt();
        System.out.println("The prime numbers from 2 to " n " are: ");
        for(int j = 2; j <= n; j  ) {
        cont = 0;
            for(i = 1;i <= j; i  ) {
               if(j % i == 0) {
                    cont  ;        
               }
            } if(cont == 2) {
                   System.out.print(j "  ");   
                }
        }
    }
}

CodePudding user response:

Your for loop

for (int j = 2; j <= n; j  ){
    //Do whatever
}

can be easily re-written as a while loop

int j = 2;

while (j <= n){
    //Do whatever
    j  ;
}

A for loop is basically a specialized while loop that lets you define a starting variable, a stop condition, and an increment value.

A basic while loop only has a stop condition, so in order to accomplish what a for loop does, you just need to define the starting variable j and the incremental j

CodePudding user response:

  public static boolean isPrime(int n) {
     if(n == 1) {
         return false;
     } 
     
     for(int i = 2; i <= (long) Math.sqrt(n); i  ) {
         if(n % i == 0) {
             return false;
         }
     }
         return true;
 }

 public static void printPrimes(int endPoint) {
     int i = 2;
     System.out.printf("The prime numbers between 2 and %d are:%n", endPoint);
     while(i <= endPoint) {
         if(isPrime(i)) {
             System.out.println(i);
         }
         i  ;
     }
 }

This is my first submission here so please forgive me if this is formatted poorly. Echoing what mmartinez04 said, the while loop functions very similarly to a for as far as iterating through a sequence of integers in this particular situation. The key aspect is ensuring that you are incrementing i in the body of the loop to prevent an endless loop.

  • Related