如何检查数字中的所有数字是否为素数。?
例如:
输入: 2375
输出:是的,它是素数
输入: 2345
输出:不是素数
答案 0 :(得分:1)
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int n=1235;
int r,i,s,flag=0;
while(n>0)
{
r=n%10; /* extracting the digits one by one */
n=n/10;
flag=0;
s=(int) Math.sqrt(r); /*taking the sqrt of extracted number */
for(i=2;i<=s;i++) /*iterating from 2 to sqrt of the extracted number, if the extracted number is divisible by any number in the iteration then it is not prime*/
{
if(r%i==0)
{
flag=1; /*if it is divisible break out */
break;
}
}
if(flag==1) /*break out of while loop also if it is divisible */
{
System.out.println("not prime");
break;
}
}
if(flag==0) /*if the loop completed without breaking, it means the number is prime */
System.out.println("prime");
}
}
我在评论中解释了代码