I need to calculate the value for the following function:
$$f(n) = -1 + 2 - 3 + ... + -1^n$$
The time limit to calculate a given value of \$n\$ is less than 1 second. My approach does not meet that requirement at large sizes, for example \$f(1000000000)\$.
My code:
program A486;
uses wincrt, sysutils;
var
n: LongInt;
function f(n : LongInt): LongInt;
var
i : LongInt;
//Result : LongInt;
begin
Result:= 0;
for i:= 1 to n do
if i mod 2 = 0 then
Result += i
else
Result -= i;
//f:= Result;
end;
begin
readln(n);
writeln(f(n));
//readkey()
end.
Is there a better way I can do this?