[ create a new paste ] login | about

Link: http://codepad.org/xmNuWMyb    [ raw code | output | fork | 1 comment ]

C++, pasted on Aug 27:
#include <cstdio>

template<class T>
T abs(T val) {
    return val >= 0 ? val : -val;
}

int invert(int n) {
    int x = -abs(2*n);
    const int incr = n > 0 ? -1 : 1;
    while (x++ < 0) {
        n += incr;
    }   
    return n;
}


void test(int n) {
    printf("%d inverted is %d\n", n, invert(n));
}

int main(int argc, char** argv) {
    test(1);
    test(22);
    test(-22);
    test(55);
    test(0);
    return 0;
}


Output:
1
2
3
4
5
1 inverted is -1
22 inverted is -22
-22 inverted is 22
55 inverted is -55
0 inverted is 0


Create a new paste based on this one


Comments:
posted by voidwarranty on Aug 27
Invert, inverse, etc. have a different meaning in math than negation.

See: http://en.wikipedia.org/wiki/Inverse_%28mathematics%29
reply