+ 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; }
6 Respuestas
+ 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
+ 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.
+ 3
Thanks but I think I found the formula Console.WriteLine("\tAnswer is equal to " + ((arg * (arg - 1)))/2);
+ 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?
+ 2
Also if your for loop works with '<=' instead of '<', you should replace the (-1) in the formula with (+1) and it will work