chap2_5.cpp 934 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include "utils.h"
  2. #include <limits>
  3. bool is_size_ok(int size) {
  4. if (size <= 0 || size > 1024) {
  5. cout << "size is invalid!" << endl;
  6. return false;
  7. }
  8. else {
  9. return true;
  10. }
  11. }
  12. vector<u32>* fibon_seq(int size) {
  13. static vector<u32> elems;
  14. if (!is_size_ok(size)) {
  15. return 0;
  16. }
  17. int current_size = elems.size();
  18. if (size > current_size) {
  19. for (int ix = current_size; ix < size; ++ix) {
  20. if (ix < 2) {
  21. elems.push_back(1);
  22. }
  23. else {
  24. int value_ix = elems[ix - 1] + elems[ix - 2];
  25. elems.push_back(value_ix);
  26. }
  27. }
  28. }
  29. return &elems;
  30. }
  31. bool fibon_elem(int position, u32& elem) {
  32. vector<u32>* fibon_vector = fibon_seq(position);
  33. if (fibon_vector) {
  34. elem = (*fibon_vector)[position-1]; //index overflow
  35. return true;
  36. }
  37. else {
  38. elem = 0;
  39. return false;
  40. }
  41. }
  42. int main() {
  43. u32 elem = 0;
  44. bool ret = fibon_elem(100, elem);
  45. if (ret) {
  46. cout << "elem is" << elem << endl;
  47. }
  48. return 0;
  49. }