English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce programme, vous apprendrez à afficher les nombres premiers entre deux intervalles donnés (bas et haut). Vous apprendrez à utiliser les boucles while et for en Java pour cela.
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 this 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 prime.
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 and1It is not a prime number. The statement condition is:
if (!flag && low != 0 && low != 1)