'How to Find Prime Number in Java?
Hello
I have java project that user need to enter int = number and find prime number.
Problem: When I Enter 10 Does't Print Any Thing.
public class Prime_Numbers {
public static void main(String[] args)
{
// Scanner
Scanner scan = new Scanner(System.in);
// Variables
int num = 10, i = 2;
// Ask User For Input
System.out.println("Please Enter Number: ");
num = scan.nextInt();
while(i <= num/2)
{
if(num % i == 2)
{
System.out.println(num);
break;
}
}
}
}
Solution 1:[1]
If you look at the if statement inside your while-loop, nothing inside gets executed. The reason is the condition of the if-statement: (num % i == 2). Since 10%2 is not equal to 2, nothing will be printed. Rather, it is equal to 0. If you are trying to check if num is an even number, then change num % i == 2 to num % i == 0.
Solution 2:[2]
You can try this code :
import java.util.Scanner;
public class PrimeNumberExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number : ");
int number = scanner.nextInt();
boolean flag = false;
for(int count=2; count<number; count++) {
if(number%count == 0) {
flag = true;
break;
}
}
if(!flag) {
System.out.println(number + " is Prime");
} else {
System.out.println(number + " is Not Prime");
}
}
}
Solution 3:[3]
maybe you can try find prime number code
public class PrimeExample{
public static void main(String args[]){
int i,m=0,flag=0;
int n=5;//it is the number to be checked
m=n/2;
if(n==0||n==1){
System.out.println(n+" is not prime number");
}else{
for(i=2;i<=m;i++){
if(n%i==0){
System.out.println(n+" is not prime number");
flag=1;
break;
}
}
if(flag==0) {
System.out.println(n+" is prime number");
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | luk2302 |
Solution 2 | |
Solution 3 | Asen |