Getting Constraints are inconsistent and cannot be solved error.while generating prime number

My guess is that the constraint solver assigns a random value to “a” before it calls the “prime” function.

A way to work around this is to create a list of prime numbers in the range of interest, add them to a queue, then randomly select one of the primes from the queue.


class data_frame;
   int unsigned a;
   rand int unsigned idx;
   int unsigned primes [$];

   constraint c2 { idx < (primes.size() - 1); }

   function new;
      for (int i=0; i<=50; i++) if (is_prime(i)) primes.push_back(i);
   endfunction

   function void post_randomize;
      a = primes[idx];
   endfunction

   function bit is_prime (int unsigned number);
      if(number <= 1)
        return 0;

      for(int i = 2; i < number; i++)begin
         if(number % i == 0)
           return 0;
      end

      return 1;
   endfunction
endclass

module test;
   data_frame d_f1;
   initial begin
      d_f1 = new();
      repeat(60) begin
         if (d_f1.randomize()) begin
            $display("Value of a=%0d", d_f1.a);
         end else begin
            $display("a= randomize failed");
         end
      end
   end
endmodule