Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • forval loop not breaking

    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:
    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
    Any help is greatly appreciated.

    Alfonso.
    Alfonso Sanchez-Penalver

  • #2
    I can't tell you how many times I've made the same mistake. Stata's -break- command is not at all like a break statement in C/C++. Stata's -break- command controls whether Stata will respond to the keyboard's break key, which is not helpful here.

    What you want is

    continue, break

    which is Stata's way of saying "done with this loop, get out here."

    (Doubly confusing since C/C++ also have a continue statement, which, again, has nothing to do with what Stata's -continue- statement does.)

    Comment


    • #3
      Wow! Thanks Clyde. Yes, I was thinking that break worked in the same manner as in C/C++/C#, and yes it is extremely confusing because of the continue statement in those languages. Thanks again for the explanation.
      Alfonso Sanchez-Penalver

      Comment

      Working...
      X