int k=1;
while (k<n){
k=k+C //where C is a constant and >=2
}
This will take (n-1)/C
steps: write u = (k-1)/C. Then, k = Cu + 1 and the statement becomes
u=0;
while(u < (n-1)/C) {
u=u+1
}
Hence the while loop is O(n)
(since C
is constant)
EDIT: let me try to explain it the other way around.
Start with a dummy variable u
. The loop
u=0;
while(u < MAX) {
u = u+1
}
runs MAX
times.
When you let MAX = (n-1) / C
, the loop is
u=0;
while(u < (n-1)/C) {
u=u+1
}
And that runs (n-1)/C
times.
Now, the check u < (n-1)/C
is equivalent to C*u < n-1
or C*u + 1 < n
, so the loop is equivalent to
u=0;
while(C*u + 1 < n) {
u=u+1
}
Now, suppose that we rewrote this loop in terms of a variable k = C * u + 1
. Then,
u=0;
k=1; // C * 0 + 1 = 1
The loop looks like
while(C*u + 1 < n) {
while(k < n) {
and the inner condition is
u=u+1
k=k+C //C * (u+1) + 1 = C * u + 1 + C = old_k + C
Putting it all together:
int k=1;
while (k<n){
k=k+C
}
takes (n-1)/C
steps.