Decrease a variable until a number is reached zero

2.1k Views Asked by At

I have a while loop in a programming language. I am looking for an elegant way to subtract an intial value by one until the new value reachs zero, until zero the substrations return always zero.

I am using module operation but I have some problem to get the right solution For example:

// R project language
s = 5
for(i in 1:10) {
    s = s - ((s) %% (s-1))
    print(s)
}
[1] 4
[1] 3
[1] 2
[1] 2
[1] 2
[1] 2
[1] 2
[1] 2
[1] 2
[1] 2

what I wish is:

[1] 4
[1] 3
[1] 2
[1] 1
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
2

There are 2 best solutions below

1
On
// R project language
s = 5
for(i in 1:10) {
    if (s > 0) { s = s - 1 }
    print(s)
}
0
On

If your programming language has ternary operators, consider:

$$s = s-((s==0)?0:1).$$

Or maybe

$$s = s-\max(s, 0)$$

But really you should probably just use an if statement to verify that the value is not $0$ before subtracting.