fork download
  1. #include <iostream>
  2. #include <cmath>
  3. #include <iomanip>
  4. #include <limits>
  5.  
  6. using namespace std;
  7.  
  8. const double FUEL_PER_MILE = 2.125;
  9.  
  10. // Function to check if a number is an odd prime
  11. bool isOddPrime(int n) {
  12. if (n < 2 || n % 2 == 0) return false; // Exclude even numbers and 2
  13. for (int i = 3; i <= sqrt(n); i += 2) {
  14. if (n % i == 0) return false;
  15. }
  16. return true;
  17. }
  18.  
  19. // Function to simulate the trip and determine the stranded location
  20. double simulateTrip(double initialFuel, bool printOutput = false) {
  21. double fuel = initialFuel;
  22. int location = 0;
  23.  
  24. while (fuel >= 0) {
  25. if (printOutput) {
  26. cout << "LOCATION: " << location << " FUEL: " << fixed << setprecision(6) << fuel << endl;
  27. cout << flush; // Ensure output is printed immediately
  28. }
  29.  
  30. if (isOddPrime(location)) {
  31. fuel += location; // Refuel at odd prime mile markers
  32. if (printOutput) {
  33. cout << location << " FUEL ADDED AT ODD PRIME MILE MARKER" << endl;
  34. cout << flush;
  35. }
  36. }
  37.  
  38. fuel -= FUEL_PER_MILE; // Consume fuel per mile
  39.  
  40. if (fuel < 0) {
  41. return location + (fuel / FUEL_PER_MILE); // Return exact stranded location
  42. }
  43.  
  44. location++;
  45. }
  46. return 9999999; // Use a large number instead of infinity for compatibility
  47. }
  48.  
  49. int main() {
  50. double minFuel = 6.375; // Based on your calculations
  51.  
  52. // Verify that 6.375 is indeed enough
  53. double result = simulateTrip(minFuel);
  54. if (result == 9999999) {
  55. cout << "Minimum starting fuel: " << fixed << setprecision(6) << minFuel << endl;
  56. } else {
  57. cout << "ERROR: 6.375 is not enough fuel!" << endl;
  58. }
  59.  
  60. // Part 2: Simulate with one drop less fuel
  61. double strandedLocation = simulateTrip(minFuel - 0.0001, true);
  62. cout << "Final stranded location with one drop less fuel: " << fixed << setprecision(6) << strandedLocation << endl;
  63.  
  64. return 0;
  65. }
  66.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
ERROR: 6.375 is not enough fuel!
LOCATION: 0    FUEL: 6.374900
LOCATION: 1    FUEL: 4.249900
LOCATION: 2    FUEL: 2.124900
Final stranded location with one drop less fuel: 1.999953