Answer to Question #65372 in Java | JSP | JSF for M.K

Question #65372
Need a programm:
The program asks for a integer number. If its a prime number then it has to say „Prime number“.If its not then the programm has to say „number -(inserted number)- is not a prime number and divides with: …“. It has to say ALL the numbers the inserted number divides with.
1
Expert's answer
2017-02-18T14:25:16-0500
import java.util.Scanner;

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

System.out.print("Please, enter a positive integer number: ");
int num = input.nextInt();

if (isPrime(num)) {
System.out.println("Prime number");
} else {
printDivisors(num);
}
}

public static boolean isPrime(int n) {
if (n < 2) {
return false;
}

for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}

return true;
}

public static void printDivisors(int n) {
System.out.print("number " + n + " is not a prime number and divides with: ");

for (int i = 1; i <= n; i++) {
if (n % i == 0) {
System.out.print(i + " ");
}
}

System.out.println();
}
}

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
APPROVED BY CLIENTS