fork download
  1. import math
  2.  
  3. FUEL_PER_MILE = 2.125
  4.  
  5. # Function to check if a number is an odd prime
  6. def is_odd_prime(n):
  7. if n < 2 or n % 2 == 0:
  8. return False
  9. for i in range(3, int(math.sqrt(n)) + 1, 2):
  10. if n % i == 0:
  11. return False
  12. return True
  13.  
  14. # Function to simulate the trip
  15. def simulate_trip(initial_fuel, print_output=False):
  16. fuel = initial_fuel
  17. location = 0
  18.  
  19. while fuel >= 0:
  20. if print_output:
  21. print("LOCATION: {:<2} FUEL: {:<.6f}".format(location, fuel))
  22.  
  23. fuel -= FUEL_PER_MILE # Consume fuel per mile
  24. if print_output:
  25. print("{:.3f} FUEL BURNED".format(FUEL_PER_MILE))
  26.  
  27. if is_odd_prime(location):
  28. fuel += location # Add fuel at odd prime mile markers
  29. if print_output:
  30. print("{} FUEL ADDED AT ODD PRIME MILE MARKER".format(location))
  31.  
  32. if fuel < 0:
  33. return location + (fuel / FUEL_PER_MILE) # Exact stranded location
  34.  
  35. location += 1
  36.  
  37. return float('inf') # If never stranded, return infinity
  38.  
  39. # Minimum fuel needed to never get stranded
  40. min_fuel = 7.0 # Starting with 7.0 units of fuel
  41.  
  42. # Verify if 7.0 is enough
  43. result = simulate_trip(min_fuel, print_output=True)
  44.  
  45. if result == float('inf'):
  46. print("Minimum starting fuel: {:.6f}".format(min_fuel))
  47. else:
  48. print("ERROR: 7.0 is not enough fuel!")
  49.  
  50. # Part 2: Simulate with one drop less fuel
  51. stranded_location = simulate_trip(min_fuel - 0.0001, print_output=True)
  52. print("FINAL STRANDED LOCATION: {:.7f}".format(stranded_location))
  53.  
Success #stdin #stdout 0.01s 7184KB
stdin
Standard input is empty
stdout
LOCATION: 0     FUEL: 7.000000
2.125 FUEL BURNED
LOCATION: 1     FUEL: 4.875000
2.125 FUEL BURNED
LOCATION: 2     FUEL: 2.750000
2.125 FUEL BURNED
LOCATION: 3     FUEL: 0.625000
2.125 FUEL BURNED
3 FUEL ADDED AT ODD PRIME MILE MARKER
LOCATION: 4     FUEL: 1.500000
2.125 FUEL BURNED
ERROR: 7.0 is not enough fuel!
LOCATION: 0     FUEL: 6.999900
2.125 FUEL BURNED
LOCATION: 1     FUEL: 4.874900
2.125 FUEL BURNED
LOCATION: 2     FUEL: 2.749900
2.125 FUEL BURNED
LOCATION: 3     FUEL: 0.624900
2.125 FUEL BURNED
3 FUEL ADDED AT ODD PRIME MILE MARKER
LOCATION: 4     FUEL: 1.499900
2.125 FUEL BURNED
FINAL STRANDED LOCATION: 3.7058353