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.*;importjava.util.stream.*;importjava.lang.*;importjava.io.*;publicclassSolution{publicstaticvoidmain(String[]args){/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */List<Integer>pandigitals=newArrayList<>();for(inti=1;i<10;i++){List<String>digits=IntStream.rangeClosed(1,i).mapToObj(Integer::toString).collect(Collectors.toList());List<List<String>>permutations=getPermutations(digits);for(List<String>p:permutations){intnum=Integer.parseInt(String.join("",p));if(isPrime(num)){pandigitals.add(num);}}}pandigitals.sort(Comparator.naturalOrder());try{BufferedReaderreader=newBufferedReader(newInputStreamReader(System.in));intn=Integer.parseInt(reader.readLine());for(intt=0;t<n;t++){intquery=Integer.parseInt(reader.readLine());intanswer=pandigitals.stream().filter(p->p<=query).reduce((first,second)->second).orElse(-1);System.out.println(answer!=0?Integer.toString(answer):"-1");}}catch(IOExceptionex){System.out.println("Error: "+ex.getMessage());}}staticbooleanisPrime(intn){if(n==1||(n%2==0&&n!=2)){returnfalse;}for(inti=3;i<=Math.sqrt(n);i+=2){if(n%i==0){returnfalse;}}returntrue;}staticList<List<String>>getPermutations(List<String>list){if(list.size()==1){List<List<String>>result=newArrayList<>();result.add(list);returnresult;}List<List<String>>permutations=newArrayList<>();for(inti=0;i<list.size();i++){Stringa=list.get(i);List<String>remaining=newArrayList<>(list.subList(0,i));remaining.addAll(list.subList(i+1,list.size()));List<List<String>>subPermutations=getPermutations(remaining);for(List<String>subPerm:subPermutations){List<String>permutation=newArrayList<>();permutation.add(a);permutation.addAll(subPerm);permutations.add(permutation);}}returnpermutations;}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #41: Pandigital prime
You are viewing a single comment's thread. Return to all comments →
JAva Code