[ create a new paste ] login | about

Link: http://codepad.org/48T0akaN    [ raw code | output | fork | 1 comment ]

mohit_at_codepad - C++, pasted on Jul 20:
// Print the sides of right angled triangle whose sides are whole numbers and the perimeter is 1000.
// Whole numbers are analogous to unsigned integers in C.
// 12 is a whole number, but 12.5 is NOT a whole number.
// What are the optimizations possible?
#include <cassert>
#include <iostream>
using namespace std;

// This function calculates the squareroot of an integer very fast
int isqrt(int num) {
  int res = 0;
  int bit = 1 << 30;

  while (bit > num) bit >>= 2;

  while (bit != 0) {
    if (num >= res + bit) {
      num -= res + bit;
      res = (res >> 1) + bit;
    } else res >>= 1;
    bit >>= 2;
  }
  return res;
}

// Main logic in this program
int main() {
  const int p = 1000;
  int numIterations = 0;
  for(int i = 4, j = 2; j < p / 2; i += 2 * ++j - 1) {
    assert(i == j * j);  // j = 2, 3, 4.... i = 4, 9, 16...

    for(int k = 1, m = 1; (i >= k) && (j + m < 2 * p / 3); k += 2 * ++m - 1) {
      // k is also a square number
      ++numIterations;
      assert(k = m * m); // m = 1, 2, 3..j j = 1, 2, 9...i
      const int s = i + k;  // s = c * c = a * a + b * b
      const int n = isqrt(s);
      if(n * n != s) continue;  // Sum is not a perfect square
      if( p % (j + m + n) == 0 ) { // Side is not a multiple of p
        const int f = p / (j + m + n); // Multiplication factor needed to multiply the perimeter
        cout << '(' << (f * j)
             << ',' << (f * m)
             << ',' << (f * n)
             << ')' << endl;
       cout << "Number of iterations = " << numIterations << endl;
        return 0;
      } // End of if
    } // End of inner for
  } // End of outer for
  cout << "Answer not found. Number of iterations = " << numIterations << endl;
  return -1;
}


Output:
1
2
(375,200,425)
Number of iterations = 112


Create a new paste based on this one


Comments:
posted by mohit_at_codepad on Apr 16
http://codepad.org/eZSolgsw in 39 iterations
reply