From 2cdbca922ad97e2bee84e2c78343defd221d5b59 Mon Sep 17 00:00:00 2001 From: Daniele Fucini Date: Sun, 29 Sep 2019 18:03:11 +0200 Subject: [PATCH] Correct problem 9 solution --- C/p009.c | 42 +++++++++++++++++++++++++++++++++--------- Python/p009.py | 37 +++++++++++++++++++++++++++++++------ 2 files changed, 64 insertions(+), 15 deletions(-) diff --git a/C/p009.c b/C/p009.c index c086eae..d0ff0d1 100644 --- a/C/p009.c +++ b/C/p009.c @@ -11,10 +11,11 @@ #include #include #include +#include "projecteuler.h" int main(int argc, char **argv) { - int a, b, c, m, n, found = 0; + int a, b, c, tmpa, tmpb, tmpc, i, m, n, found = 0; double elapsed; struct timespec start, end; @@ -24,16 +25,39 @@ int main(int argc, char **argv) * Euclid's formula, until the one where a+b+c=1000 is found.*/ for(m = 2; found == 0; m++) { - for(n = 1; n < m; n++) + for(n = 1; n < m && !found; n++) { - a = m * m - n * n; - b = 2 * m * n; - c = m * m + n * n; - - if(a + b + c == 1000) + if(gcd(m, n) == 1 && (m % 2 == 0 && n % 2 != 0 || m % 2 != 0 && n % 2 == 0)) { - found = 1; - break; + a = m * m - n * n; + b = 2 * m * n; + c = m * m + n * n; + + if(a + b + c == 1000) + { + found = 1; + break; + } + + i = 2; + + do + { + tmpa = a * i; + tmpb = b * i; + tmpc = c * i; + + if(tmpa + tmpb + tmpc == 1000) + { + a = tmpa; + b = tmpb; + c = tmpc; + found = 1; + break; + } + + i++; + }while(tmpa + tmpb + tmpc < 1000); } } } diff --git a/Python/p009.py b/Python/p009.py index 64125c9..2dbb14c 100644 --- a/Python/p009.py +++ b/Python/p009.py @@ -10,6 +10,8 @@ # # Find the product abc. +from math import gcd + from timeit import default_timer def main(): @@ -23,14 +25,37 @@ def main(): # Euclid's formula, until the one where a+b+c=1000 is found. while not found: for n in range(1, m): - a = m * m - n * n - b = 2 * m * n - c = m * m + n * n - - if a + b + c == 1000: - found = 1 + if found == 1: break + if gcd(m, n) == 1 and (m % 2 == 0 and n % 2 != 0 or m % 2 != 0 and n % 2 == 0): + a = m * m - n * n + b = 2 * m * n + c = m * m + n * n + + if a + b + c == 1000: + found = 1 + break + + i = 2 + + while True: + tmpa = a * i + tmpb = b * i + tmpc = c * i + + if tmpa + tmpb + tmpc == 1000: + a = tmpa + b = tmpb + c = tmpc + found = 1 + break + + if tmpa + tmpb + tmpc > 1000: + break + + i = i + 1 + m = m + 1 end = default_timer()