Write a program that prompts the user for an integer and then prints out all coward numbers up to
that integer. For example, when the user enters 20, the program should print: 3 4 6 8 12 14 18 20.
Recall that a number is a prime number if it is not divisible by any number except 1 and itself.
Hint: Use Nested Loop to solve this problem. Outer Loop iterations must start from 3 and ideally inner
loop iterations must start from 2.
Coward Number: Number whose previous number is not divisible by any number other than 1
and number itself.
Instructions:
1. Create a program called CowardNumbers.java.
2. Create appropriate variables and assign values using a Scanner object.
import java.util.Scanner;
public class CowardNumbers {
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in);
int N = keyBoard.nextInt();
System.out.print("3 ");
for (int number = 3; number <= N; number++) {
boolean is_Prime = true;
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
is_Prime = false;
break;
}
}
if (is_Prime) {
System.out.print((number + 1) + " ");
}
}
keyBoard.close();
}
}
Comments
Leave a comment