Playing with loops : one
#1

A question like this was on my ICT exams,

Quote:

In a loop like shown above, what would p be at the end?

So I was being bored at home and made something real quick.


pawn Код:
CMD:loop(playerid, params[])
{
new p;
new a;
new piet;
if(sscanf(params, "ii", p,a)) return SCM(playerid, COLOR_GREY, "USAGE: /loop [1-50] [1-15]");
if(a < 0 || a > 15) return SCM(playerid, COLOR_GREY, "USAGE: /loop [1-50] [1-15]");
if(p < 0 || p > 50) return SCM(playerid, COLOR_GREY, "USAGE: /loop [1-50] [1-15]");
piet = p;
for(new i = 0; i <= a; i++)
{
   p = p + i;
}
new string[128];
format(string, sizeof(string), "[DEBUG] Using Starting number %d and loop size %d the result would be %d", piet, a, p);
print(string);
printf("[DEBUG] Set P %d,Set A %d ||==||==|| P = P + A gives P = %d while loop = A", piet, a, p);
SCM(playerid, COLOR_WHITE, string);
return 1;
}


Example:

/loop 2 5 would give:

2 + 0 = 2
2 + 1 = 3
3 + 2 = 5
5 + 3 = 8
8 + 4 = 12
12 + 5 = 17


P would be 17 at the end of this loop.




that's basically what I do when I'm bored
Reply
#2

Neat, but what's the use?
Reply
#3

Quote:

Neat, but what's the use?

Its to understand more how maths/C++/pawn works, and it's just fun to figure out new stuff ^.^, atleast thats what I think.


Quote:
Originally Posted by ******
Посмотреть сообщение
They're called triangular numbers and there's a much simpler way to do it:

pawn Код:
p = (a * a + a) / 2;
Or:

pawn Код:
p = a * (a + 1) / 2;
This is referred to as "algorithmic complexity" - a loop takes "N" time to get the answer because it has to repeat some arbitrary code many times. A formula takes "1" time because it only has to do one thing. Look up "Big-O" (big-oh) notation.
But if I used a starting number for p, like I did in my example, I would need to edit that formula right?
As in something like this:


pawn Код:
p = (a * a + p) / 2;
Or maybe not the above one, but I can't figure out the right formula atm, as the one you gave me wouldn't work for starting numbers, or am I being an idiot now? (I just woke up ^.^)
Reply
#4

Quote:
Originally Posted by ******
Посмотреть сообщение
Then you would just change "p = " to "p += " in my code. The majority of the calculation is still the same.
Ow right, I wasn't paying attention there as I woke up exactly 5 minutes ago.
Will give it a shot to see if the results are the same
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)