Hi,
I am trying to write a code in System verilog to “get a random prime number less than the given input”?
Can someone help me with the logic for this, or how to use constraints here?
Hi,
I am trying to write a code in System verilog to “get a random prime number less than the given input”?
Can someone help me with the logic for this, or how to use constraints here?
In reply to Akhil Mehta:
The example I gave you shows how to get primes less that 200. change 200 to your input,
In reply to Akhil Mehta:
module test;
class prime_number;
int limit;
rand int a[];
constraint abc {a.size==limit; }
constraint cba { foreach(a[i])
a[i]==prime(i);}
function int prime( int g);
if(g <= 1)return 2;
for(int i=2;i<g;i++)
if(g%i==0)
return 2; //if it is not a prime number ,returning 2 which is one of prime
prime=g;
endfunction
function void post_randomize();
a=a.unique;
endfunction
endclass
prime_number pri;
initial
begin
pri=new;
pri.limit = 290;
void'(pri.randomize);
$display("%p",pri);
end
endmodule
In reply to Shubhabrata:
In reply to Akhil Mehta:
module test;
class prime_number;
int limit;
rand int a[];
constraint abc {a.size==limit; }
constraint cba { foreach(a[i])
a[i]==prime(i);}
function int prime( int g);
if(g <= 1)return 2;
for(int i=2;i<g;i++)
if(g%i==0)
return 2; //if it is not a prime number ,returning 2 which is one of prime
prime=g;
endfunction
function void post_randomize();
a=a.unique;
endfunction
endclass
prime_number pri;
initial
begin
pri=new;
pri.limit = 290;
void'(pri.randomize);
$display("%p",pri);
end
endmodule
Can someone please explain how below part working in above code ?
for(int i=2;i<g;i++)
if(g%i==0)
return 2; //if it is not a prime number ,returning 2 which is one of prime
prime=g;
Thanks in advance!!
In reply to Harshad:
The function prime(arg) is returning the argument passed into it if the argument is a prime number, otherwise it returns 2. This assumes the limit is going to be 2 or greater. Then post_randomize() eliminates all the duplicate 2’s.
This might be a clearer way to write the class
class prime_number;
int limit;
rand int a[];
constraint abc {a.size==limit; limit > 1; }
constraint cba { foreach(a[i])
if (prime(i))
a[i] == i;
else
a[i] == 2;
}
function bit prime( int g);
if(g <= 1) return 0; // not a prime
for(int i=2;i<g;i++)
if(g%i==0)
return 0; // not a prime
return 1; // is a prime
endfunction
function void post_randomize();
a=a.unique; // gert rid of duplicate 2's
endfunction
endclass
In reply to dave_59:
Thanks Dave ! but still I confused that how below part is execute
for(int i=2;i<g;i++)
if(g%i==0)
return 0; // not a prime
return 1; // is a prime
My understanding is, suppose if g=3 and i=2 then 3%2 is not equal to zero because remainder is 1 and function will return 0(not prime) but here g=3 is a prime number so this is wrong
In reply to Harshad:
When g=3, the for-loop iterates once with i=2. 3%2 does not equal 0, so the for-loop terminates executing return 1 (is a prime).