47 lines
1.1 KiB
C++
47 lines
1.1 KiB
C++
|
#include <iostream>
|
||
|
#include <climits>
|
||
|
//original function:
|
||
|
long f(int n)
|
||
|
{
|
||
|
if(n == 0) return 0;
|
||
|
else if(n < 0) return -f(-n);
|
||
|
else return f(n-1) + 3*n*(n-1);
|
||
|
}
|
||
|
|
||
|
//My implementation:
|
||
|
long f2(int n)
|
||
|
{
|
||
|
long result = 0;
|
||
|
if(n<0)
|
||
|
{
|
||
|
for (long i = 0; i<=n*-1; i++)
|
||
|
{
|
||
|
result += -(3*i*i-3*i);
|
||
|
}
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
for (long i = 0; i<=n; i++)
|
||
|
{
|
||
|
result += 3*i*i-3*i;
|
||
|
}
|
||
|
}
|
||
|
return result;
|
||
|
}
|
||
|
|
||
|
int main()
|
||
|
{
|
||
|
//brute force check 😅:
|
||
|
for (int i = -20000; i != INT_MAX ; i++){
|
||
|
if(f(i) != f2(i))
|
||
|
{
|
||
|
std::cout << i << " WRONG!!😦 " << f(i) << " != "<< f2(i) << "\n";
|
||
|
/* Its seems like my implementation works well, until it reches the number 26756, there it
|
||
|
outputs 19154179862460 instead of 19149884895164 and the error only gets worse from there.
|
||
|
I have no idea why this happens, and i dont have time to figure it out 🙃
|
||
|
Please enlighten me if you can!
|
||
|
*/
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
}
|