fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int getHighestTwoPowerFactor(int from);
  5. int getNearestTwoPower(int from);
  6.  
  7. int getTrains(int from, int to) {
  8. cout << from << " ";
  9. int count = 1;
  10.  
  11. if(from == 0) {
  12. from = getNearestTwoPower(to);
  13. count++;
  14. cout << from << " ";
  15. } else if(from % 2 != 0) {
  16. from++;
  17. count++;
  18. cout << from << " ";
  19. }
  20.  
  21. if(from == to)
  22. return count;
  23.  
  24. int getHighestTwoPowerFactor = 1;
  25.  
  26. while(true) {
  27. getHighestTwoPowerFactor = ::getHighestTwoPowerFactor(from);
  28. from += getHighestTwoPowerFactor;
  29. count++;
  30. if(from > to) {
  31. from -= getHighestTwoPowerFactor;
  32. count--;
  33. break;
  34. } else if(from == to) {
  35. cout << from << " ";
  36. return count;
  37. }
  38. cout << from << " ";
  39. }
  40.  
  41. while(from < to) {
  42. while(from + getHighestTwoPowerFactor > to) {
  43. getHighestTwoPowerFactor /= 2;
  44. }
  45. from += getHighestTwoPowerFactor;
  46. count++;
  47. cout << from << " ";
  48. }
  49. cout << endl;
  50. return count;
  51. }
  52.  
  53. int getHighestTwoPowerFactor(int from) {
  54. if((from & (from - 1)) == 0)
  55. return from;
  56.  
  57. int count = 0;
  58. while(from % 2 == 0) {
  59. from >>= 1;
  60. count++;
  61. }
  62. return 1 << count;
  63. }
  64.  
  65. int getNearestTwoPower(int from) {
  66. if((from & (from - 1)) == 0)
  67. return from;
  68.  
  69. int count = 0;
  70. while(from != 0) {
  71. from >>= 1;
  72. count++;
  73. }
  74. return 1 << (count - 1);
  75. }
  76.  
  77. int main() {
  78. int from = 3, to = 17;
  79. int result = getTrains(from, to);
  80. cout << "Total steps: " << result << endl;
  81. return 0;
  82. }
Success #stdin #stdout 0.01s 5208KB
stdin
Standard input is empty
stdout
3 4 8 16 17 
Total steps: 5