Search code examples
pythonc++algorithmpython-3.xtriangle-count

C++ and Python version of the same algorithm giving different result


The following code is an algorithm to determine the amount of integer triangles, with their biggest side being smaller or equal to MAX, that have an integer median. The Python version works but is too slow for bigger N, while the C++ version is a lot faster but doesn't give the right result.

When MAX is 10, C++ and Python both return 3.

When MAX is 100, Python returns 835 and C++ returns 836.

When MAX is 200, Python returns 4088 and C++ returns 4102.

When MAX is 500, Python returns 32251 and C++ returns 32296.

When MAX is 1000, Python returns 149869 and C++ returns 150002.

Here's the C++ version:

#include <cstdio>
#include <math.h>

const int MAX = 1000;

int main()
{
    long long int x = 0;
    for (int b = MAX; b > 4; b--)
    {
        printf("%lld\n", b);
        for (int a = b; a > 4; a -= 2){
            for (int c = floor(b/2); c < floor(MAX/2); c+=1)
            {
                if (a+b > 2*c){
                    int d = 2*(pow(a,2)+pow(b,2)-2*pow(c,2));
                    if (sqrt(d)/2==floor(sqrt(d)/2))
                        x+=1;
                }
            }
            }
    }
    printf("Done: ");       
    printf("%lld\n", x);
}

Here's the original Python version:

import math

def sumofSquares(n):
    f = 0
    for b in range(n,4,-1):
        print(b)
        for a in range(b,4,-2):
            for C in range(math.ceil(b/2),n//2+1):
                if a+b>2*C:
                    D = 2*(a**2+b**2-2*C**2)
                    if (math.sqrt(D)/2).is_integer():
                        f += 1
    return f

a = int(input())
print(sumofSquares(a))
print('Done')

I'm not too familiar with C++ so I have no idea what could be happening that's causing this (maybe an overflow error?).

Of course, any optimizations for the algorithm are more than welcome!


Solution

  • The issue is that the range for your c (C in python) variables do not match. To make them equivalent to your existing C++ range, you can change your python loop to:

    for C in range(int(math.floor(b/2)), int(math.floor(n/2))):
        ...
    

    To make them equivalent to your existing python range, you can change your C++ loop to:

    for (int c = ceil(b/2.0); c < MAX/2 + 1; c++) {
        ...
    }
    

    Depending on which loop is originally correct, this will make the results match.