Skip to content

Commit b5802a8

Browse files
committed
feat: Check if a number is prime and print its factors using break and continue
🧠 Logic: - Given a number (143), loop from 2 to number-1 to check for divisibility. - If divisible, print it's not prime and use `break` to exit early. - If the loop reaches the end without finding a divisor, the number is prime. - Use a `while` loop to find and print all factors of the number. - Skip non-factors using `continue`. - Print the factor when found. 🎯 Focus: Demonstrates usage of `break` to exit a loop and `continue` to skip to the next iteration. Signed-off-by: Somesh diwan <[email protected]>
1 parent 88da4e1 commit b5802a8

File tree

1 file changed

+7
-13
lines changed

1 file changed

+7
-13
lines changed
Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
1-
public class BreakAndContinue
2-
{
3-
public static void main(String[] args)
4-
{
1+
public class BreakAndContinue {
2+
public static void main(String[] args) {
53
int number = 143;
64
System.out.println("Let's check if " + number + " is a prime number.");
7-
for (int divisor = 2; divisor < number; divisor++)
8-
{
5+
6+
for (int divisor = 2; divisor < number; divisor++) {
97
int remainder = number % divisor; //The modulo operator gives the remainder of the division involved.
10-
if (remainder == 0)
11-
{
8+
if (remainder == 0) {
129
System.out.println("The number is not prime since it is divisible by " + divisor + ".");
1310
break; //Exit the for loop
1411
}
@@ -18,16 +15,13 @@ public static void main(String[] args)
1815

1916
System.out.println("\nLet's check how many factors it has.");
2017
int factor = 2;
21-
while (factor < number)
22-
{
18+
while (factor < number) {
2319
int remainder = number % factor; //The modulo operator gives the remainder of the division involved.
2420
factor++;
25-
if (remainder != 0)
26-
{
21+
if (remainder != 0) {
2722
continue; //Proceed to the next iteration of the loop, ignoring the rest of this iteration.
2823
}
2924
System.out.println(factor-1 + " is a factor of 143.");
3025
}
31-
3226
}
3327
}

0 commit comments

Comments
 (0)