English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriais Básicos de Java

Java controle de fluxo

Java array

Java orientação a objetos (I)

Java orientação a objetos (II)

Java orientação a objetos (III)

Tratamento de Exceções Java

Java lista (List)

Java fila (Queue)

Java conjuntos Map

Java conjuntos Set

Java entrada e saída (I/O)

Java Reader/Writer

Outros tópicos Java

Programa Java exibindo primos entre intervalos

Java Examples Comprehensive

Neste programa, você aprenderá a exibir primos entre dois intervalos dados (baixo e alto). Você aprenderá a usar loops while e for em Java para fazer isso.

Exemplo: exibir primos entre dois intervalos

public class Prime {
    public static void main(String[] args) {
        int low = 20, high = 50;
        while (low < high) {
            boolean flag = false;
            for (int i = 2; i <= low/2; ++i) {
                //Condition for non-prime numbers
                if (low % i == 0) {
                    flag = true;
                    break;
                }
            }
            if (!flag && low != 0 && low != 1)
                System.out.print(low + "");
            ++low;
        }
    }
}

When running the program, the output is:

23 29 31 37 41 43 47

In this program, each number between low and high is tested for primality. The inner for loop checks if the number is a prime number.

You can check:Java Program to Check Prime Numbersfor more information.

Compared to the interval, the difference in checking individual prime numbers is that you need to reset flag = false in each iteration of the while loop.

Note: If the check is from 0 to10interval. So, you need to exclude 0 and1. Because 0 and1Is not a prime number. The statement condition is:

if (!flag && low != 0 && low != 1)

Java Examples Comprehensive