I want to generate an array of prime numbers. So far I’ve tried two approaches to achieve this.
class a;
rand int ary[5];
constraint prime_const {
foreach(ary[i]) {
ary[i] == prime_gen(50); // approach1
ary[i] inside {[2:50]} && (is_prime(ary[i])==1); //approach 2
}
}
//returns 1 if the provided value is a prime number
function int is_prime(int a);
for (int c = 2; c <= a - 1; c++) begin
if (a%c == 0) return 0;
end
return 1;
endfunction
//returns a random prime number within given range
function int prime_gen(int range);
int p_q[$];
int ret;
for (int i=0; i<=range; i++) begin
if (is_prime(i)) p_q.push_back(i);
end
p_q.shuffle();
ret = p_q.pop_front();
p_q.delete();
return ret;
endfunction
endclass
Output:
with approach 1: ary:'{3, 3, 3, 3, 3}
All the array elements are same. Seems like the function prime_gen function is called once.
with approach 2: Got an array of prime numbers as expected for some seed, but not always, randomization fails sometimes.
Can someone explain to me what went wrong here?