Hi everyone, I'm creating a function to get the prime number closest (but below) a number I want. This becomes useful for Halton draws, since drawing with prime numbers is better, and I can just use an integer of the number of draws I want. I thus have created a program, isprime, that checks whether an argument is prime or not, and another function, getprime, that uses isprime to get the prime number closest to the number wanted. The problem I'm having is that even though I request to break out of the loop once it has reached that value, the program doesn't and I can't figure out why. Below are the two programs:
Any help is greatly appreciated.
Alfonso.
Code:
*! isprime v1.0.0 ASanchez-Penalver 06apr2014 program define isprime, rclass version 13.1 tempname p scalar `p' = 1 * Notice that 2 and 3 are primes but that half of both of them are less * than 2 so if those values are passed this loop will never be ran and * the program will return true, i.e. 1 local max = floor(sqrt(`1')) forval i = 2(1)`max' { if mod(`1',`i') == 0 { scalar `p' = 0 break } } return scalar prime = `p' return scalar number = `1' end
Code:
*! getprime v1.0.0 ASanchez-Penalver 06apr2014 program define getprime, rclass version 13.1 tempname p forval i = `1'(-1)2 { isprime `i' if `r(prime)' == 1 { scalar `p' = `i' break } } return scalar pnum = `p' return scalar rnum = `1' end
Alfonso.
Comment