#include using namespace std; //*********************************************************** // HackerRank Prepare > Mathematics > Fundamentals: Handshake //*********************************************************** // Example: There are 3 attendees, p1, p2, and p3. p1 shakes hands // with p2 and p3. p2 shakes hands with p3. Now they have all shaken // hands after 3 handshakes. // 3 choose 2 => 3! / 2! (3 - 2)! = 3; int handshake(int n) { auto fact = [](int n) { auto fact_impl = [](int n, auto& fact_ref) { if(n == 1 || n == 0) return 1; int fact = 1; while (n > 0) { fact *= n--; } return fact; // return n * fact_ref(n-1, fact_ref); }; return fact_impl(n, fact_impl); }; int r = 2; // using a rescursive or O(n) factorial function causes a runtime // error in hackerrank. Reduce the n choose r equation n!/r!(n-r)! // by substituting r = 2 to n * (n-1)/2 // n! / 2! (n-2)! = n * (n-1) * (n-2) ... / 2! (n-2) * (n-3) ... // = n * (n-1) / 2 return n == 1 ? 0 : fact(n)/(r*fact(n-r)); } int main() { vector,vector>> testCases = { // input expected { {1,2}, {0,1} } }; for (auto test: testCases) { vector& inputV = get<0>(test); vector& expectedV = get<1>(test); for (size_t i = 0; i < inputV.size(); i++) { int n = inputV.at(i); int result = handshake(n); int expected = expectedV.at(i); cout << n << endl; cout << result << endl; cout << expected << endl; cout << "----------\n"; } } }