We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
importjava.io.*;importjava.util.*;publicclassSolution{privatestaticboolean[]prime=null;publicstaticvoidmain(String[]args){/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */Scannerin=newScanner(System.in);intn=in.nextInt();intk=in.nextInt();intlimit=2500000;introot=(int)Math.ceil(Math.sqrt(limit));prime=generatePrimes(root,limit);for(inti=2;i<=n;i++){ArrayList<TreeSet>list=newArrayList<TreeSet>();if(!prime[i]){for(intj=0;j<k;j++){if(!prime[i+j]){TreeSets=primeFactorize(i+j);if(s.size()==k)list.add(s);elsebreak;}elsebreak;}}if(list.size()==k)System.out.println(i);}}publicstaticTreeSet<Integer>primeFactorize(Integern){try{TreeSet<Integer>set=newTreeSet<Integer>();for(inti=2;i<=n/i;i++){while(n%i==0){set.add(i);n/=i;}}if(n>1)set.add(n);returnset;}catch(Exceptione){throwe;}}publicstaticboolean[]generatePrimes(introot,intlimit){boolean[]prime=newboolean[limit+1];prime[2]=true;prime[3]=true;//Sieve of Atkin for prime number generationfor(intx=1;x<root;x++){for(inty=1;y<root;y++){intn=4*x*x+y*y;if(n<=limit&&(n%12==1||n%12==5))prime[n]=!prime[n];n=3*x*x+y*y;if(n<=limit&&n%12==7)prime[n]=!prime[n];n=3*x*x-y*y;if((x>y)&&(n<=limit)&&(n%12==11))prime[n]=!prime[n];}}for(inti=5;i<=root;i++){if(prime[i]){for(intj=i*i;j<limit;j+=i*i){prime[j]=false;}}}returnprime;}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #47: Distinct primes factors
You are viewing a single comment's thread. Return to all comments →
JAva Code