[ create a new paste ] login | about

Link: http://codepad.org/OWLx1B4v    [ raw code | output | fork ]

mohit_at_codepad - C++, pasted on Jun 1:
/// Find pythagorus triplet in an array
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cmath>
using namespace std;

static int sq_(int n) { return n*n; }
static int rt(int n) { return static_cast<int>( sqrt(n) ); }

void print_triplet(int asq, int bsq, int csq) {
  cout << '('
       << rt(asq) << ','
       << rt(bsq) << ','
       << rt(csq)
       << ')' << endl;
}

void findPythagorean(int *arr, int sz) {
  sort(arr, arr + sz);
  transform(arr, arr+sz, arr, sq_);
  const int &k = sz;
  while(--sz >= 2) {
    int i = 0, j = sz - 1;
    const int &kval = arr[k];
    while(i < j) {
      const int sum = arr[i] + arr[j];
      if(sum == kval) print_triplet(arr[i], arr[j], arr[k]);
      if(sum >= kval) --j;
      else ++i;
    }
  }
}

int main() {
  srand(0);
  const int arrsize = 500;
  int arr[arrsize] = {0};
  for(int i = 0; i < 500; ++i) arr[i] = rand() % 2000;
  findPythagorean(arr, arrsize);

  return 0;
}


Output:
(183,1856,1865)
(183,1856,1865)
(600,1750,1850)
(280,1386,1414)
(813,1084,1355)
(813,1084,1355)
(624,1170,1326)
(540,1155,1275)
(600,1125,1275)
(364,1155,1211)
(723,964,1205)
(675,900,1125)
(624,715,949)
(43,924,925)
(336,850,914)
(335,804,871)
(315,756,819)
(315,756,819)
(481,600,769)
(304,690,754)
(304,690,754)
(259,660,709)
(315,624,699)
(50,624,626)
(342,456,570)
(27,364,365)
(219,292,365)
(84,245,259)


Create a new paste based on this one


Comments: