Having troubles with math | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Having troubles with math

I met this question some hours ago while completing challenges, and I find it very hard to make all the visualization in my head without taking 2 or 3 minutes, probably because I'm bad at math in general but .. Is there some formula for solving this without having to imagine visually all the five loop iterations and their values? // arg = 5 public static int myFunc(int arg) { int result = 0; for (int i = 0; i < arg; i++) { result = result + i; } return result; }

24th Jun 2018, 11:02 PM
Todor Yanev
Todor Yanev - avatar
5 Answers
+ 11
Also, very generally, when arg is even you could use: (1+arg)*(arg/2) when arg is odd you could use: (1+arg)*((arg-1)/2)+median(1 to arg) the above assumes the condition <=, otherwise you would just substitute arg-1 for arg in the above pseudo code
25th Jun 2018, 1:37 AM
Edward Russell
Edward Russell - avatar
+ 4
First you have to note that the loop will iterate up to 4 from 0.result is being incremented with the values 0 to 4 and the resulting sum is output....So basically you would just have to add (0+1+2+3+4) hope it answers your question.
24th Jun 2018, 11:28 PM
Nsamba Abubaker
Nsamba Abubaker - avatar
+ 3
Thanks but I think I found the formula Console.WriteLine("\tAnswer is equal to " + ((arg * (arg - 1)))/2);
24th Jun 2018, 11:44 PM
Todor Yanev
Todor Yanev - avatar
+ 2
For instance, when I pass 5 as an argument, I already know the answer is not going to be less than 5 because the loop ends at 4 < 5 and then ++, so I already know half of the answer how I find the other half?
24th Jun 2018, 11:10 PM
Todor Yanev
Todor Yanev - avatar
+ 2
Also if your for loop works with '<=' instead of '<', you should replace the (-1) in the formula with (+1) and it will work
25th Jun 2018, 12:14 AM
Todor Yanev
Todor Yanev - avatar