Created
May 5, 2015 10:27
-
-
Save stephen-maina/b5e9d1031edf394b0ac4 to your computer and use it in GitHub Desktop.
very fast
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Set; | |
import java.util.HashSet; | |
class Solution { | |
public int[] solution(int N, int[] P, int[] Q) { | |
// write your code in Java SE 8 | |
int result[]=new int [Q.length]; | |
int semi[]=sieve(N); | |
for(int index=0;index<P.length;index++){ | |
result[index]=semi[Q[index]]-semi[P[index]-1]; | |
} | |
return result; | |
} | |
public int[] sieve(int N){ | |
int[] semi=new int[N+1]; | |
int resultCount=0; | |
Set<Integer> primemul=new HashSet<Integer>(); | |
int [] primes=new int[N+1]; | |
int index=2; | |
while(index<=N){ | |
if(primes[index]==0){ | |
primemul.add(index); | |
int multiples=index*index; | |
while(multiples<=N&&multiples>2){ | |
if(primes[multiples]==0){ | |
primes[multiples]=index; | |
} | |
multiples+=index; | |
} | |
}else{ | |
if(!primemul.isEmpty()){ | |
int check=(int)index/primes[index]; | |
if(primemul.contains(check)){ | |
resultCount++; | |
} | |
} | |
} | |
semi[index]=resultCount; | |
index++; | |
} | |
return semi; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment