-
Notifications
You must be signed in to change notification settings - Fork 13
/
ForExample6.java
48 lines (37 loc) · 970 Bytes
/
ForExample6.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package lessons.loops.forloops;
public class ForExample6 {
public static void main(String[] args)
{
run();
}
public static void run()
{
java.util.Scanner kb = new java.util.Scanner(System.in);
System.out.print("Number:");
int val = kb.nextInt();
if (isPrime(val))
System.out.printf("%d. is prime. ", getPrimeIndex(val));
else
System.out.println("please enter the prime number");
}
public static int getPrimeIndex(int n)
{
int count = 1;
for (int i = 1; i <= n; i += 2) {
if (isPrime(i))
count++;
}
return count;
}
public static boolean isPrime(long a)
{
if (a <= 1)
return false;
if (a % 2 == 0)
return a == 2;
for (long i = 3; i * i <= a; i += 2)
if (a % i == 0)
return false;
return true;
}
}