Answer to Question #233857 in Java | JSP | JSF for jeffy

Question #233857

Question-1 [10 Points]

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.


1
Expert's answer
2021-09-06T13:17:26-0400
import java.util.Scanner;


public class CowardNumbers {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int N = input.nextInt();

		for (int i = 2; i <= N; i++) {
			boolean isPrime = true;
			// ideally inner loop iterations must start from 2.
			for (int j = 2; j <= i / 2; j++) {
				if (i % j == 0) {
					isPrime = false;
					break;
				}
			}
			if (isPrime) {
				System.out.print((i+1) + " ");
			}


		}
		// close Scanner
		input.close();
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS