fork download
  1.  
  2. #include <vector>
  3. #include <iostream>
  4.  
  5. // Here is your recursive function!
  6. // Ok ok, that's cheating...
  7. unsigned int fact(unsigned int n)
  8. {
  9. if(n == 0) return 1;
  10. else return n * fact(n - 1);
  11. }
  12.  
  13. unsigned int binom(unsigned int n, unsigned k)
  14. {
  15. // Not very optimized (useless multiplications)
  16. // But that's not really a problem: the number will overflow
  17. // way earlier than you will notice any performance problem...
  18. return fact(n) / (fact(k) * fact(n - k));
  19. }
  20.  
  21. std::vector<unsigned int> pascal(unsigned n)
  22. {
  23. std::vector<unsigned int> res;
  24. for(unsigned int k = 0; k <= n; k++)
  25. res.push_back(binom(n,k));
  26. return res;
  27. }
  28.  
  29. std::ostream& operator<<(std::ostream& out, const std::vector<unsigned int>& v)
  30. {
  31. for(unsigned int t = 0; t < v.size(); t++)
  32. out << v[t] << " ";
  33. return out;
  34. }
  35.  
  36. int main()
  37. {
  38. for(unsigned int t = 0; t < 6; t++)
  39. std::cout << pascal(t) << "\n";
  40. }
  41.  
  42.  
Success #stdin #stdout 0.02s 2812KB
stdin
Standard input is empty
stdout
1 
1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 
1 5 10 10 5 1