fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. final static int BASE = 10;
  11. static boolean[] isPrime;
  12. public static void main (String[] args) throws java.lang.Exception
  13. {
  14. System.in));
  15. int noOfTestCaseT = Integer.parseInt(reader.readLine().trim());
  16. StringBuilder output = new StringBuilder(noOfTestCaseT);
  17. int [][] testCases = new int[noOfTestCaseT][2];
  18. int maxNum = 0;
  19.  
  20. for (int i=0;i<noOfTestCaseT;i++) {
  21. String[] tempInt = reader.readLine().split(" ");
  22. testCases[i][0] = Integer.parseInt(tempInt[0].trim());
  23. testCases[i][1] = Integer.parseInt(tempInt[1].trim());
  24. if (testCases[i][1] > maxNum)
  25. maxNum = testCases[i][1];
  26. }
  27.  
  28. isPrime = generatePrime(maxNum+1);
  29.  
  30. int [] cumulativeCount = new int[maxNum+1];
  31. int count = 1;
  32. cumulativeCount[2] = 1;
  33. for (int i=3;i<=maxNum;i++) {
  34. if (((i&1) == 1) && isPrime[i] && !isDigitOnePresent(i))
  35. count++;
  36. cumulativeCount[i] = count;
  37. }
  38.  
  39. for (int i=0;i<noOfTestCaseT;i++) {
  40. int n = testCases[i][0];
  41. int m = testCases[i][1];
  42. if (n > 0)
  43. n--;
  44. int primesWithoutOnes = cumulativeCount[m] - cumulativeCount[n];
  45. if (primesWithoutOnes == 0) {
  46. output.append("-1\n");
  47. } else {
  48. output.append(primesWithoutOnes);
  49. output.append("\n");
  50. }
  51. }
  52. System.out.print(output);
  53. }
  54.  
  55. private static boolean isDigitOnePresent(int i) {
  56. while(i !=0 ){
  57. int temp = i % BASE;
  58. if( temp == 1)
  59. return true;
  60. i /= BASE;
  61. }
  62. return false;
  63. }
  64.  
  65. private static boolean[] generatePrime(int maxNum) {
  66. int root = (int) Math.sqrt(maxNum);
  67. boolean[] isPrime = new boolean[maxNum];
  68. Arrays.fill(isPrime, true);
  69. isPrime[0] = false; isPrime[1] = false;
  70. for (int i = 3; i < root; i+=2) {
  71. if (isPrime[i]) {
  72. int increment = i+i;
  73. for (int j = i * i ; j < maxNum; j = j + increment) {
  74. isPrime[j] = false;
  75. }
  76. }
  77. }
  78. return isPrime;
  79. }
  80. }
Success #stdin #stdout 0.1s 320320KB
stdin
1
276 297
stdout
4