Advertisement
AlexandruDu

Problema 5

Nov 2nd, 2020
850
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4. int st[51], n, p, primes[51];
  5. ofstream fout("prime.out");
  6.  
  7. int check(int x) {
  8.     for (int d = 2; d * d <= x; d++)
  9.         if (x % d == 0)
  10.             return 0;
  11.     return 1;
  12. }
  13.  
  14. void gen() {
  15.     int cp = 0;
  16.     for (int x = 11; cp < p; x += 2)
  17.         if (check(x))
  18.             primes[++cp] = x;
  19. }
  20.  
  21. void tipar(int k) {
  22.     for (int i = 1; i <= k; i++)
  23.         fout << primes[st[i]] << ' ';
  24.     fout << endl;
  25. }
  26.  
  27. int solutie(int k) {
  28.     return k == p;
  29. }
  30.  
  31. int validare(int k) {
  32.     for (int i = 1; i < k; i++)
  33.         if (st[i] == st[k])
  34.             return 0;
  35.     return 1;
  36. }
  37.  
  38. void bktr() {
  39.     int k = 1;
  40.     st[k] = 0;
  41.     while (k) {
  42.         if (st[k] < n) {
  43.             st[k]++;
  44.             if (validare(k)) {
  45.                 if (solutie(k))
  46.                     tipar(k);
  47.                 else {
  48.                     k++;
  49.                     st[k] = 0;
  50.                 }
  51.             }
  52.         }
  53.         else
  54.             k--;
  55.     }
  56. }
  57.  
  58. int main() {
  59.     cin >> n >> p;
  60.     gen();
  61.     swap(n, p);
  62.     bktr();
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement