# What is the simplest way to create $n$ steps for a loop?

I have a series of numbers:

$$1,2,3,4,5,\ldots,n\quad\text{(n numbers)}$$

It can also be:

$$0,1,2,3,\ldots,n-1\quad\text{(n numbers)}$$

I need to divide those $n$ numbers to $K$ steps such as $1\ldots K$ steps.

It is guaranteed that $n\mod k=0$

For example, if I have:

$$1,2,3,4,5,6,7,8,9$$

Then $n=9$.

Now I want $3$ steps: $1,2,3$ so $K=3$. It will look like:

$$\text{step1} = 1,2,3 \\ \text{step2} = 4,5,6 \\ \text{step3} = 7,8,9$$

I want to create a function that will get a number and return to which step it belongs.

I have managed to do this with a simple computer program:

for (int i=0;i<9;i++)  //0,1,2,3,4,5,6,7,8  which is 9 numbers
{
Console.WriteLine ((i-(i%3))/3  +1);
}


Result:

1
1
1
2
2
2
3
3
3


Great.

…but it won't work for any sequence. For example, if I choose $1,2,3,4,5,6,7,8,9$ and not $0,1,2,3,4,5,6,7,8$:

for (int i=1;i<=9;i++)
{
Console.WriteLine ((i-(i%3))/3 );
}


It yields…

0
0
1
1
1
2
2
2
3


Besides the fact that my solution doesn't work, I believe there is a simple/elegant way to check each number's step.

This looks too complicated:

(i-(i%3))/3+1

I don't want to use Math functions like round, ceil or floor. I want to do it with pure math.

Is there any better way to calculate the step for a number?

• You want to do it with pure math, but without using math functions. Huh? Commented Feb 17, 2015 at 12:09
• @GerryMyerson I want to use ( if it's possible) +,-,*,/,%,^, . Round ,truncate , Ceil , floor are "complex" functions. which im trying to avoid. Commented Feb 17, 2015 at 12:12
• @GerryMyerson Look at my first example ( (i-(i%3))/3). I didnt use any complex function and still got the right result. Commented Feb 17, 2015 at 12:13
• Note that the integer division operation is anything but "pure math". see stackoverflow.com/questions/12240228/…. Also not that for an integer $i$ that $(i-(i\%3))/3 == i/3$ in C. Commented Feb 17, 2015 at 15:36
• @JohnJoy You're right Commented Feb 17, 2015 at 15:43

for (int i=1;i<=9;i++)

{

int k=i-1;

Console.WriteLine ((k-(k%3))/3 );

}

Note: your first result should be: 000111222. If you do want 111222333 then do

Console.WriteLine ((k-(k%3))/3 +1);