Question -- Problem 94, Project Euler -- Python -- Almost equilateral triangles
*It is easily proved that no equilateral triangle exists with integral length sides and integral area. However, the almost equilateral triangle 5-5-6 has an area of 12 square units.
We shall define an almost equilateral triangle to be a triangle for which two sides are equal and the third differs by no more than one unit.
Find the sum of the perimeters of all almost equilateral triangles with integral side lengths and area and whose perimeters do not exceed one billion (1,000,000,000).*
Output: 518408346
I have a very inefficient solution and it is as follows:
- I tried to bruteforce(it took a considerable amount of time) (using a for loop)
- Then I added in the condition to check whether it was a triangle (sum of two sides is greater than the third)
- Next, I defined the values in a perimeter variable and also used simple geometry for the area variable
- Next, to check whether they were valid, for the perimeter I used a type method to check whether it was int and since I couldn't do the same for area(since even if it was an integer, it would be part of the float class), I used modulo 1 == 0 to check if it was an integer
- If it satisfied the condition, I added it to my final 'sum of perimeter' variable.
The code is as follows:
import time
start = time.time()
plst = 0
o = 100000
for i in range(1,o):
j = i+1
if 2*i > j and j > 0:
p = 2*i + j
a = 0.5 * j* ((i**2 - (j/2)**2)**0.5)
# if p > 100:
# break
# else:
# pass
if type(p) == int and a % 1 == 0:
print(i)
print('\t', p)
plst += p
else:
pass
else:
pass
for k in range(1,o):
b = k-1
if 2*k > b and b > 0:
p = 2*k + b
a = 0.5 * b* ((k**2 - (b/2)**2)**0.5)
# if p > 100:
# break
# else:
# pass
if type(p) == int and a % 1 == 0:
print(k)
print('\t', p)
plst += p
else:
pass
else:
pass
print(plst)
print(f'{time.time() - start} seconds')
Note:
Yes, I know my o value is 100000.
Yes, i commented out the condition to check whether the perimeter variable crossed a billion, as I was facing problems before reaching one billion.
Don't mind the commented code. I have two problems for which I require help In order of precedence
When I run the code, uptill 10000, it works fine and fast, but as soon as I jump up to 100000, i realise that there are some unnecesary values that are popping up in the output.(like 93686,93686,93687)
A. I call it unnecesary because when I searched this up, one website showed a table of values that will finally result in the answer and 93686 was not a part of it.(This is the website, https://blog.dreamshire.com/project-euler-94-solution/)
B. But I could not find a mistake in my program and I tried out the area of these 'unnecesary' numbers and surprisingly the area turned out to be an integer and that surprised me and this resulted in me getting a wrong answer
So could someone explain what the mistake is?
2. Could someone give me an efficient solution with a proper explanation in Python?
I use python 3.8