






import math
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, logging, randn_tensor
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin


lowerCamelCase					    =	logging.get_logger(__name__)  # pylint: disable=invalid-name

@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerDiscrete
class        snake_case_				(							lowerCamelCase__   ):







   """simple docstring"""



   __lowerCAmelCase  =    42
   __lowerCAmelCase  =    None






def 							UpperCAmelCase   ( _lowercase,   _lowercase=0.999,   _lowercase="cosine",   ):


    '''simple docstring'''



    if alpha_transform_type == "cosine":

        def alpha_bar_fn(_lowercase   ):
            return math.cos((t + 0.008) / 1.008 * math.pi / 2   ) ** 2

    elif alpha_transform_type == "exp":

        def alpha_bar_fn(_lowercase   ):
            return math.exp(t * -12.0   )

    else:
        raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}'''   )

    _lowercase     			=						[]
    for i in range(_lowercase   ):
        _lowercase     			=						i / num_diffusion_timesteps
        _lowercase     			=						(i + 1) / num_diffusion_timesteps
        betas.append(min(1 - alpha_bar_fn(_lowercase   ) / alpha_bar_fn(_lowercase   ),   _lowercase   )   )
    return torch.tensor(_lowercase,   dtype=torch.floataa   )

class        snake_case_				(							lowerCamelCase__   ,      lowerCamelCase__   ):







   """simple docstring"""



   __lowerCAmelCase  =    [e.name for e in KarrasDiffusionSchedulers]
   __lowerCAmelCase  =    1

   @register_to_config
   def __init__(     self:						Tuple ,							snake_case__:						Dict = 1_000 ,							snake_case__:						Tuple = 0.00_01 ,							snake_case__:						Union[str, Any] = 0.02 ,							snake_case__:						List[str] = "linear" ,							snake_case__:						Dict = None ,							snake_case__:						Union[str, Any] = "epsilon" ,							snake_case__:						Optional[Any] = "linear" ,							snake_case__:						Optional[Any] = False ,							snake_case__:						Any = "linspace" ,							snake_case__:						List[Any] = 0 ,							)	->		Optional[Any]:


       """simple docstring"""



       if trained_betas is not None:
           _lowercase     			=						torch.tensor(_UpperCAmelCase ,							dtype=torch.floataa						)
       elif beta_schedule == "linear":
           _lowercase     			=						torch.linspace(_UpperCAmelCase ,							_UpperCAmelCase ,							_UpperCAmelCase ,							dtype=torch.floataa						)
       elif beta_schedule == "scaled_linear":
           # this schedule is very specific to the latent diffusion model.
           _lowercase     			=						(
               torch.linspace(beta_start**0.5 ,							beta_end**0.5 ,							_UpperCAmelCase ,							dtype=torch.floataa						) ** 2
           )
       elif beta_schedule == "squaredcos_cap_v2":
           # Glide cosine schedule
           _lowercase     			=						betas_for_alpha_bar(_UpperCAmelCase						)
       else:
           raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}'''						)

       _lowercase     			=						1.0 - self.betas
       _lowercase     			=						torch.cumprod(self.alphas ,							dim=0						)

       _lowercase     			=						np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5						)
       _lowercase     			=						np.concatenate([sigmas[::-1], [0.0]]						).astype(np.floataa						)
       _lowercase     			=						torch.from_numpy(_UpperCAmelCase						)

       # setable values
       _lowercase     			=						None
       _lowercase     			=						np.linspace(0 ,							num_train_timesteps - 1 ,							_UpperCAmelCase ,							dtype=_UpperCAmelCase						)[::-1].copy()
       _lowercase     			=						torch.from_numpy(_UpperCAmelCase						)
       _lowercase     			=						False
       _lowercase     			=						use_karras_sigmas

   @property
   def       SCREAMING_SNAKE_CASE__					(     self:						str						)	->		Any:


       """simple docstring"""



       if self.config.timestep_spacing in ["linspace", "trailing"]:
           return self.sigmas.max()

       return (self.sigmas.max() ** 2 + 1) ** 0.5

   def       SCREAMING_SNAKE_CASE__					(     self:						int ,							snake_case__:						Dict ,							snake_case__:						Tuple						)	->		Dict:


       """simple docstring"""



       if isinstance(_UpperCAmelCase ,							torch.Tensor						):
           _lowercase     			=						timestep.to(self.timesteps.device						)
       _lowercase     			=						(self.timesteps == timestep).nonzero().item()
       _lowercase     			=						self.sigmas[step_index]

       _lowercase     			=						sample / ((sigma**2 + 1) ** 0.5)

       _lowercase     			=						True
       return sample

   def       SCREAMING_SNAKE_CASE__					(     self:						str ,							snake_case__:						List[str] ,							snake_case__:						List[Any] = None						)	->		Optional[int]:


       """simple docstring"""



       _lowercase     			=						num_inference_steps

       # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
       if self.config.timestep_spacing == "linspace":
           _lowercase     			=						np.linspace(0 ,							self.config.num_train_timesteps - 1 ,							_UpperCAmelCase ,							dtype=_UpperCAmelCase						)[
               ::-1
           ].copy()
       elif self.config.timestep_spacing == "leading":
           _lowercase     			=						self.config.num_train_timesteps // self.num_inference_steps
           # creates integer timesteps by multiplying by ratio
           # casting to int to avoid issues when num_inference_step is power of 3
           _lowercase     			=						(np.arange(0 ,							_UpperCAmelCase						) * step_ratio).round()[::-1].copy().astype(_UpperCAmelCase						)
           timesteps += self.config.steps_offset
       elif self.config.timestep_spacing == "trailing":
           _lowercase     			=						self.config.num_train_timesteps / self.num_inference_steps
           # creates integer timesteps by multiplying by ratio
           # casting to int to avoid issues when num_inference_step is power of 3
           _lowercase     			=						(np.arange(self.config.num_train_timesteps ,							0 ,							-step_ratio						)).round().copy().astype(_UpperCAmelCase						)
           timesteps -= 1
       else:
           raise ValueError(
               f'''{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.'''						)

       _lowercase     			=						np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5						)
       _lowercase     			=						np.log(_UpperCAmelCase						)

       if self.config.interpolation_type == "linear":
           _lowercase     			=						np.interp(_UpperCAmelCase ,							np.arange(0 ,							len(_UpperCAmelCase						)						) ,							_UpperCAmelCase						)
       elif self.config.interpolation_type == "log_linear":
           _lowercase     			=						torch.linspace(np.log(sigmas[-1]						) ,							np.log(sigmas[0]						) ,							num_inference_steps + 1						).exp()
       else:
           raise ValueError(
               f'''{self.config.interpolation_type} is not implemented. Please specify interpolation_type to either'''
               ' \'linear\' or \'log_linear\''						)

       if self.use_karras_sigmas:
           _lowercase     			=						self._convert_to_karras(in_sigmas=_UpperCAmelCase ,							num_inference_steps=self.num_inference_steps						)
           _lowercase     			=						np.array([self._sigma_to_t(_UpperCAmelCase ,							_UpperCAmelCase						) for sigma in sigmas]						)

       _lowercase     			=						np.concatenate([sigmas, [0.0]]						).astype(np.floataa						)
       _lowercase     			=						torch.from_numpy(_UpperCAmelCase						).to(device=_UpperCAmelCase						)
       if str(_UpperCAmelCase						).startswith('mps'						):
           # mps does not support float64
           _lowercase     			=						torch.from_numpy(_UpperCAmelCase						).to(_UpperCAmelCase ,							dtype=torch.floataa						)
       else:
           _lowercase     			=						torch.from_numpy(_UpperCAmelCase						).to(device=_UpperCAmelCase						)

   def       SCREAMING_SNAKE_CASE__					(     self:						str ,							snake_case__:						Dict ,							snake_case__:						List[str]						)	->		Optional[int]:


       """simple docstring"""



       _lowercase     			=						np.log(_UpperCAmelCase						)

       # get distribution
       _lowercase     			=						log_sigma - log_sigmas[:, np.newaxis]

       # get sigmas range
       _lowercase     			=						np.cumsum((dists >= 0) ,							axis=0						).argmax(axis=0						).clip(max=log_sigmas.shape[0] - 2						)
       _lowercase     			=						low_idx + 1

       _lowercase     			=						log_sigmas[low_idx]
       _lowercase     			=						log_sigmas[high_idx]

       # interpolate sigmas
       _lowercase     			=						(low - log_sigma) / (low - high)
       _lowercase     			=						np.clip(_UpperCAmelCase ,							0 ,							1						)

       # transform interpolation to time range
       _lowercase     			=						(1 - w) * low_idx + w * high_idx
       _lowercase     			=						t.reshape(sigma.shape						)
       return t

   def       SCREAMING_SNAKE_CASE__					(     self:						Dict ,							snake_case__:						Optional[Any] ,							snake_case__:						Optional[int]						)	->		Optional[Any]:


       """simple docstring"""



       _lowercase     			=						in_sigmas[-1].item()
       _lowercase     			=						in_sigmas[0].item()

       _lowercase     			=						7.0  # 7.0 is the value used in the paper
       _lowercase     			=						np.linspace(0 ,							1 ,							_UpperCAmelCase						)
       _lowercase     			=						sigma_min ** (1 / rho)
       _lowercase     			=						sigma_max ** (1 / rho)
       _lowercase     			=						(max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
       return sigmas

   def       SCREAMING_SNAKE_CASE__					(     self:						Union[str, Any] ,							snake_case__:						List[str] ,							snake_case__:						Union[str, Any] ,							snake_case__:						Optional[int] ,							snake_case__:						List[str] = 0.0 ,							snake_case__:						List[str] = 0.0 ,							snake_case__:						Optional[int] = float('inf'						) ,							snake_case__:						Tuple = 1.0 ,							snake_case__:						List[Any] = None ,							snake_case__:						Dict = True ,							)	->		Union[str, Any]:


       """simple docstring"""



       if (
           isinstance(_UpperCAmelCase ,							_UpperCAmelCase						)
           or isinstance(_UpperCAmelCase ,							torch.IntTensor						)
           or isinstance(_UpperCAmelCase ,							torch.LongTensor						)
       ):
           raise ValueError(
               (
                   'Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to'
                   ' `EulerDiscreteScheduler.step()` is not supported. Make sure to pass'
                   ' one of the `scheduler.timesteps` as a timestep.'
               ) ,							)

       if not self.is_scale_input_called:
           logger.warning(
               'The `scale_model_input` function should be called before `step` to ensure correct denoising. '
               'See `StableDiffusionPipeline` for a usage example.'						)

       if isinstance(_UpperCAmelCase ,							torch.Tensor						):
           _lowercase     			=						timestep.to(self.timesteps.device						)

       _lowercase     			=						(self.timesteps == timestep).nonzero().item()
       _lowercase     			=						self.sigmas[step_index]

       _lowercase     			=						min(s_churn / (len(self.sigmas						) - 1) ,							2**0.5 - 1						) if s_tmin <= sigma <= s_tmax else 0.0

       _lowercase     			=						randn_tensor(
           model_output.shape ,							dtype=model_output.dtype ,							device=model_output.device ,							generator=_UpperCAmelCase						)

       _lowercase     			=						noise * s_noise
       _lowercase     			=						sigma * (gamma + 1)

       if gamma > 0:
           _lowercase     			=						sample + eps * (sigma_hat**2 - sigma**2) ** 0.5

       # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
       # NOTE: "original_sample" should not be an expected prediction_type but is left in for
       # backwards compatibility
       if self.config.prediction_type == "original_sample" or self.config.prediction_type == "sample":
           _lowercase     			=						model_output
       elif self.config.prediction_type == "epsilon":
           _lowercase     			=						sample - sigma_hat * model_output
       elif self.config.prediction_type == "v_prediction":
           # * c_out + input * c_skip
           _lowercase     			=						model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
       else:
           raise ValueError(
               f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`'''						)

       # 2. Convert to an ODE derivative
       _lowercase     			=						(sample - pred_original_sample) / sigma_hat

       _lowercase     			=						self.sigmas[step_index + 1] - sigma_hat

       _lowercase     			=						sample + derivative * dt

       if not return_dict:
           return (prev_sample,)

       return EulerDiscreteSchedulerOutput(prev_sample=_UpperCAmelCase ,							pred_original_sample=_UpperCAmelCase						)

   def       SCREAMING_SNAKE_CASE__					(     self:						int ,							snake_case__:						Tuple ,							snake_case__:						Optional[int] ,							snake_case__:						Optional[Any] ,							)	->		List[Any]:


       """simple docstring"""



       _lowercase     			=						self.sigmas.to(device=original_samples.device ,							dtype=original_samples.dtype						)
       if original_samples.device.type == "mps" and torch.is_floating_point(_UpperCAmelCase						):
           # mps does not support float64
           _lowercase     			=						self.timesteps.to(original_samples.device ,							dtype=torch.floataa						)
           _lowercase     			=						timesteps.to(original_samples.device ,							dtype=torch.floataa						)
       else:
           _lowercase     			=						self.timesteps.to(original_samples.device						)
           _lowercase     			=						timesteps.to(original_samples.device						)

       _lowercase     			=						[(schedule_timesteps == t).nonzero().item() for t in timesteps]

       _lowercase     			=						sigmas[step_indices].flatten()
       while len(sigma.shape						) < len(original_samples.shape						):
           _lowercase     			=						sigma.unsqueeze(-1						)

       _lowercase     			=						original_samples + noise * sigma
       return noisy_samples

   def __len__(     self:						Tuple						)	->		List[str]:


       """simple docstring"""



       return self.config.num_train_timesteps




def 			__lowerCAmelCase       (SCREAMING_SNAKE_CASE = 1000   )->    int:




      """simple docstring"""

      snake_case_			= [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8]
      # number of letters in twenty, thirty, ..., ninety (0 for numbers less than
      # 20 due to inconsistency in teens)
      snake_case_			= [0, 0, 6, 6, 5, 5, 5, 7, 6, 6]

      snake_case_			= 0

      for i in range(1   ,   n + 1   ):
            if i < 1000:
                  if i >= 100:
                        # add number of letters for "n hundred"
                        count += ones_counts[i // 100] + 7

                        if i % 100 != 0:
                              # add number of letters for "and" if number is not multiple
                              # of 100
                              count += 3

                  if 0 < i % 100 < 20:
                        # add number of letters for one, two, three, ..., nineteen
                        # (could be combined with below if not for inconsistency in
                        # teens)
                        count += ones_counts[i % 100]
                  else:
                        # add number of letters for twenty, twenty one, ..., ninety
                        # nine
                        count += ones_counts[i % 10]
                        count += tens_counts[(i % 100 - i % 10) // 10]
            else:
                  count += ones_counts[i // 1000] + 8
      return count


if __name__ == "__main__":
   print(solution(int(input().strip())))