Teaching Kids Programming: Videos on Data Structures and Algorithms
Proof of Pythagorean Theorem
The big square’s area is and it is equal to 4 triangls + a small square.
therefore:
Bruteforce Algorithm to Find Pythagorean Numbers
Given c – a integer, let’s find all distinct positive pairs (a smaller or equal than b and
Then, we can iterate a from 1 till b is smaller than a. We can compute the value of when a is fixed. Then, we just need to check if b is a perfect square – this can be done using inbuilt sqrt function or binary search algorithm.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | from math import sqrt def f(c): a = 1 while c * c >= 2 * a * a: b2 = c * c - a * a b = int(sqrt(b2)) if b * b == b2: print("(%d)^2 + (%d)^2 = (%d)^2" % (a, b, c)) a += 1 f(5) f(10) f(50) f(100) |
from math import sqrt def f(c): a = 1 while c * c >= 2 * a * a: b2 = c * c - a * a b = int(sqrt(b2)) if b * b == b2: print("(%d)^2 + (%d)^2 = (%d)^2" % (a, b, c)) a += 1 f(5) f(10) f(50) f(100)
Output:
(3)^2 + (4)^2 = (5)^2
(6)^2 + (8)^2 = (10)^2
(14)^2 + (48)^2 = (50)^2
(30)^2 + (40)^2 = (50)^2
(28)^2 + (96)^2 = (100)^2
(60)^2 + (80)^2 = (100)^2
Finding Pythagorean Triplets in an Array – we can use Two Pointer Algorithm or Bruteforce with Hash Set: Teaching Kids Programming – Finding Pythagorean Triplets in Array using Two Pointer or Hash Set
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: Algorithms to Sum using Distinct Positive Factorial Numbers
Next Post: Algorithms to Reverse a Graph (Adjacency List)