Advertisement
updown

The Lost Cow

Feb 2nd, 2023
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. Python:
  2.  
  3. 1. Read x and y from your input
  4.  
  5. import math
  6.  
  7. sign = 1
  8. movement = 1
  9. total_distance = 0
  10. while True:
  11. new_location = x + sign * movement
  12.  
  13. # Case 1: FJ passes Bessie
  14. if (y > x and new_location >= y) or (y < x and new_location <= y):
  15. # FJ has passed Bessie
  16. total_distance = total_distance + math.abs(x-y)
  17. break
  18.  
  19. # Case 2: FJ does not pass Bessie
  20. else:
  21. total_distance = total_distance + movement * 2
  22.  
  23. sign = sign * (-1)
  24. movement = movement * 2
  25.  
  26. output the total_distance
  27.  
  28.  
  29. C++/Java:
  30.  
  31. 1. Read x and y from your input
  32.  
  33.  
  34. int sign = 1;
  35. int movement = 1;
  36. int total_distance = 0;
  37. while (true) {
  38. int new_location = x + sign * movment;
  39.  
  40. // Case 1: FJ passes Bessie
  41. if (y > x && new_location >= y) || (y < x && new_location <= y) {
  42. // FJ has passed Bessie
  43. total_distance = total_distance + abs(x-y);
  44. break;
  45. }
  46.  
  47. // Case 2: FJ does not pass Bessie
  48. else {
  49. total_distance = total_distance + movement * 2;
  50. }
  51.  
  52. sign = sign * (-1);
  53. movement = movement * 2;
  54. }
  55.  
  56. output the total_distance
  57.  
  58. // sign = 1,-1, 1,-1, 1
  59. // movment = 1, 2, 4, 8, 16, ...
  60.  
  61. x --> x+1 -> x --> x-2 -> x --> x+4 -> x --> x-8 -> x --> x+16 -> x -> y
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement