Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. package proj1;
  2. import java.util.*;
  3.  
  4. public class P41 {
  5.  
  6. public static void main(String[] args)
  7. {
  8. Scanner in = new Scanner(System.in);
  9. System.out.println ("n =");
  10. int n = in.nextInt();
  11. System.out.println ("m =");
  12. int m = in.nextInt();
  13.  
  14. {
  15. boolean[] isPrime = new boolean [m];
  16.  
  17. for (int i = 2; i < m ; i++)
  18. isPrime[i] = true ;
  19. //Ciurul lui Eratostene pt a gasi numerele prime pana la m
  20. for ( int factor = 2 ; factor*factor < m ; factor ++)
  21. {
  22. if(isPrime[factor])
  23. {
  24. for ( int j = factor ; factor * j < m ; j++)
  25. {
  26. isPrime[factor*j] = false ;
  27. }
  28. }
  29. }
  30.  
  31. //Numaram cate numere prime avem
  32. int primes = 0 ;
  33.  
  34. for(int i = 2 ; i < m ; i++)
  35. {
  36. if(isPrime[i]) primes ++ ;
  37. }
  38.  
  39. int[] list = new int [primes];
  40. int k = 0 ;
  41.  
  42. //Adaugam numerele prime intr-o lista
  43. for(int i = 0 ; i < m ; i++)
  44. {
  45. if(isPrime[i]) list[k++] = i ;
  46. }
  47.  
  48. //Facem sumele de numere prime pana gasim perechea care adunata
  49. //da i sau pana ramanem fara numere prime
  50. for (int i = n ; i <= m ; i++)
  51. {
  52.  
  53. int l = 0 , r = k-1 ;
  54.  
  55. while ( l < r )
  56. {
  57. if ( list[l] + list[r] == i ) break ;
  58. else if( list[l] + list[r] < i ) l++;
  59. else r--;
  60. }
  61. if( i % 2 != 0)
  62. {
  63. System.out.println(i + " is odd and therefore can't be expressed as a sum of 2 prime numbers");
  64. }
  65. else
  66. {
  67. if ( list[l] + list[r] == i)
  68. {
  69. System.out.println ( i + " = " + list[l] + " + " + list[r]);
  70. }
  71. else
  72. {
  73. System.out.println ( i + " can't be expressed as a sum of two primes" );
  74. }
  75. }
  76. }
  77. }
  78.  
  79. }
  80.  
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement