Explanation of the method for determining prime numbers (cyclic structure java) in C Language experiments
Explanation of Problem Description using the method of determining prime numbers (cyclic structure java) in C Language experiments
Enter any positive integer on the keyboard and determine whether the number is a prime number.
If it is a prime number, the output "This is a prime ."
Otherwise, the output "This is not a prime ."
Input
Enter any positive integer n (1 <=n <= 1000000 ).
Output
Determine whether n is a prime number and output the result:
If n is a prime number, the output is "This is a prime ."
Otherwise, the output "This is not a prime ."
Sample Input
3
Sample Output
This is a prime.
AC code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n;
n = in.nextInt();
int i,f=1;
if (n == 1)
System.out.println("This is not a prime.");
else if(n==2)
System.out.println("This is a prime.");
else {
for(i=2;i<n;i++){
if(n%i==0){
f = 0;
}
}
if(f == 0)System.out.println("This is not a prime.");
else System.out.println("This is a prime.");
}
}
}
The result of the code is the same but the result of OLE (timeout):
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n;
n = in.nextInt();
int i;
if (n == 1)
System.out.println("This is not a prime.");
else if(n==2)
System.out.println("This is a prime.");
else {
for(i=2;i<n;i++){
if(n%i==0){
System.out.println("This is not a prime.");
break;
}
else{
System.out.println("This is a prime.");
}
}
}
}
}