English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
في هذا البرنامج، ستتعلم عرض الأعداد الأولية بين فترتين محددين (المنخفضة والعالية). ستتعلم كيفية استخدام الدوال while و for في Java لتحقيق ذلك.
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) { // Non-prime condition 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 prime.
You can check:Java Program to Check Prime NumbersFor more information.
The difference in checking individual prime numbers compared to intervals is that you need to reset flag = false in each iteration of the while loop.
NoteIf the check is from 0 to 10 intervals. Then, you need to exclude 0 and 1. Because 0 and 1 are not prime numbers. The statement condition is:
if (!flag && low != 0 && low != 1)