DEV Community

Discussion on: If - procedural, functional, object-oriented

Collapse
 
bugmagnet profile image
Bruce Axtens

I think you forgot one. I'm not sure what to call it. Perhaps "calculated". The language is this case is tbas, a dialect of BASIC.

DEF FNC(n)
    dim sum = 0
    dim i
    if n > 1 then
        for i = 2 to (n \ 2)
            sum = sum - (i * (n %% i = 0))
        next
    end if
    let FNC = sum
FNEND

Inside that for/next there's an if hidden away in the calculation.

Many dialects of BASIC do not have a boolean type but rather use the values 0 and -1 to signify false and true.

In the equation above the n %% i = 0 takes n modulus i and tests the result against 0. If true, -1 otherwise 0. The next level up in the formula therefore multiplies i by either -1 or 0 resulting in either -(i) or zero. The next level up subtracts a negative or subtracts a zero. According to standard number theory, subtracting a minus value is the same as adding a positive.

Were one to use if/then here it would convert

sum = sum - (i * (n %% i = 0))

to

if n %% i = 0 then
    sum = sum + i
end if

In tbas's case, the formulaic approach is faster than the if/then. YMMV.

Collapse
 
stereobooster profile image
stereobooster

To be fair I didn't try to least them all (if it's even possible, how to guarantee the exhaustiveness of list). Nice to have more examples