Tutte le sfide
Facile 0 risolte 0% di accettazione

Caffeine Half-Life

Find how much caffeine is left in the body after a number of hours, given its half-life.

Cosa imparerai

  • Apply exponential decay with a half-life
  • Use the power function of your language
  • Avoid integer division in a fraction of half-lives

Problema

Mostra traduzione

Caffeine leaves the body gradually: after one half-life only half of it is left, after two half-lives a quarter, and so on. The amount left after hours hours is milligrams × 0.5^(hours / half_life_hours), and the formula works for any number of hours, not only whole half-lives.

Implement caffeine_half_life(milligrams, half_life_hours, hours).

Input

milligrams: The caffeine taken at the start, in milligrams.

half_life_hours: The half-life in hours (greater than 0).

hours: How many hours have passed.

Output

Return the milligrams left after hours hours. Do not round; answers are checked to within 0.000001.

Vincoli

0 ≤ milligrams ≤ 2000

0 < half_life_hours ≤ 24

0 ≤ hours ≤ 240

Esempi

Esempio 1
Input:
milligrams = 160.0
half_life_hours = 6.0
hours = 12.0

Output atteso:
expected = 40.0
Input:
double milligrams = 160.0;
double half_life_hours = 6.0;
double hours = 12.0;

Output atteso:
double expected = 40.0;
Input:
double milligrams = 160.0;
double half_life_hours = 6.0;
double hours = 12.0;

Output atteso:
double expected = 40.0;

Spiegazione

12 hours is two half-lives, so 160 becomes 80 and then 40.

Esempio 2
Input:
milligrams = 100.0
half_life_hours = 5.0
hours = 0.0

Output atteso:
expected = 100.0
Input:
double milligrams = 100.0;
double half_life_hours = 5.0;
double hours = 0.0;

Output atteso:
double expected = 100.0;
Input:
double milligrams = 100.0;
double half_life_hours = 5.0;
double hours = 0.0;

Output atteso:
double expected = 100.0;

Spiegazione

No time has passed, so all 100 mg are still there.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

First work out how many half-lives have passed: hours divided by the half-life.

Suggerimento 2

Each half-life multiplies the amount by 0.5.

Suggerimento 3

Make sure the division is done with decimals, not whole numbers.

Complessità attesa

O(1) time, O(1) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

Ancora nessuna soluzione superata. Risolvila e prendi il primo posto.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.