From 18c066ac89eee7ea5e112c31dcc57b8e76002b06 Mon Sep 17 00:00:00 2001 From: Madhusudan.C.S Date: Sun, 11 Oct 2009 16:51:43 +0530 Subject: Almost last set of official solutions and final quiz. --- day1/exercise/aliquot.py | 19 +++++++++++++++---- day1/exercise/amicable.py | 29 ++++++++++++++++++----------- day1/exercise/even_perfect_4a.py | 14 ++++++++++++++ day1/exercise/pytriads.py | 13 ++++++++----- 4 files changed, 55 insertions(+), 20 deletions(-) create mode 100644 day1/exercise/even_perfect_4a.py (limited to 'day1/exercise') diff --git a/day1/exercise/aliquot.py b/day1/exercise/aliquot.py index f07cd77..96ea916 100644 --- a/day1/exercise/aliquot.py +++ b/day1/exercise/aliquot.py @@ -1,8 +1,19 @@ +def is_perfect_square(n): + i = 1 + while i * i < n: + i += 1 + return i * i == n, i + def aliquot(n): - sum = 0 - for i in range(1, (n/2)+1): + sum = 1 + i = 2 + + is_ps, root = is_perfect_square(n) + while i < root: if n % i == 0: - sum += i + sum += i + (n / i) + i += 1 return sum -print aliquot(14) +n = int(raw_input('Enter a number? ')) +print aliquot(n) diff --git a/day1/exercise/amicable.py b/day1/exercise/amicable.py index 0986e33..c9aea71 100644 --- a/day1/exercise/amicable.py +++ b/day1/exercise/amicable.py @@ -1,18 +1,25 @@ -import math +def is_perfect_square(n): + i = 1 + while i * i < n: + i += 1 + return i * i == n, i def aliquot(n): - sum = 0 - for i in range(1, int(math.sqrt(n))+1): + sum = 1 + i = 2 + + is_ps, root = is_perfect_square(n) + while i < root: if n % i == 0: - sum += i + n/i + sum += i + (n / i) + i += 1 return sum amicable = [] -for n in range(10000, 100000): - m = aliquot(n) - if aliquot(m) == n: - amicable.append((m, n)) -print amicable - -# please please please profile this. +n = 1000 +while n < 10000: + m = aliquot(n) + if m > n and aliquot(m) == n: + print m, n + n += 1 diff --git a/day1/exercise/even_perfect_4a.py b/day1/exercise/even_perfect_4a.py new file mode 100644 index 0000000..ccadc1c --- /dev/null +++ b/day1/exercise/even_perfect_4a.py @@ -0,0 +1,14 @@ +def all_digits_even(n): + if n < 0: n = -n + while n > 0: + if n % 2 == 1: + return False + n /= 10 + return True + +i = 46 +while i <= 94: + square = i * i + if all_digits_even(square): + print square + i += 1 diff --git a/day1/exercise/pytriads.py b/day1/exercise/pytriads.py index 916c000..4c47313 100644 --- a/day1/exercise/pytriads.py +++ b/day1/exercise/pytriads.py @@ -10,9 +10,12 @@ def gcd(a, b): else: return gcd(b, a%b) -for a in range(3, 100): - for b in range(a+1, 100): - ips, c = is_perfect_square((a * a) + (b * b)) - if ips and gcd(a, b) == 1: +a = 3 +while a < 100: + b = a + 1 + while b < 100: + is_ps, c = is_perfect_square((a * a) + (b * b)) + if is_ps and gcd(a, b) == 1: print a, b, c - + b += 1 + a += 1 -- cgit