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