


'''simple docstring'''

import os
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


if TYPE_CHECKING:
	from transformers.pipelines.conversational import Conversation

_UpperCAmelCase					:			List[Any]				     =					logging.get_logger(__name__)

_UpperCAmelCase					:			str				     =					{"""vocab_file""": """tokenizer.model"""}

_UpperCAmelCase					:			Dict				     =					{
    """vocab_file""": {
        """hf-internal-testing/llama-tokenizer""": """https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model""",
    },
    """tokenizer_file""": {
        """hf-internal-testing/llama-tokenizer""": """https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json""",
    },
}
_UpperCAmelCase					:			Optional[int]				     =					{
    """hf-internal-testing/llama-tokenizer""": 2_0_4_8,
}
_UpperCAmelCase					:			Union[str, Any]				     =					"""▁"""

_UpperCAmelCase     ,_UpperCAmelCase					:			str				     =					"""[INST]""", """[/INST]"""
_UpperCAmelCase     ,_UpperCAmelCase					:			Optional[Any]				     =					"""<<SYS>>\n""", """\n<</SYS>>\n\n"""

# fmt: off
_UpperCAmelCase					:			Any				     =					"""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\\nanswers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\\nthat your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not\\ncorrect. If you don\'t know the answer to a question, please don\'t share false information."""


class    a__					(			_snake_case   ):







				"""simple docstring"""



				__UpperCamelCase     :		Optional[int]						=						VOCAB_FILES_NAMES
				__UpperCamelCase     :		Optional[Any]						=						PRETRAINED_VOCAB_FILES_MAP
				__UpperCamelCase     :		Tuple						=						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				__UpperCamelCase     :		Optional[int]						=						['''input_ids''', '''attention_mask''']




				def __init__(self							,      __lowercase							,      __lowercase="<unk>"							,      __lowercase="<s>"							,      __lowercase="</s>"							,      __lowercase=None							,      __lowercase = None							,      __lowercase=True							,      __lowercase=False							,      __lowercase=False							,      __lowercase=True							,      **__lowercase							,      ):
										__lowerCAmelCase											=					{} if sp_model_kwargs is None else sp_model_kwargs
										__lowerCAmelCase											=					AddedToken(_a							,      lstrip=_a							,      rstrip=_a		) if isinstance(_a							,      _a		) else bos_token
										__lowerCAmelCase											=					AddedToken(_a							,      lstrip=_a							,      rstrip=_a		) if isinstance(_a							,      _a		) else eos_token
										__lowerCAmelCase											=					AddedToken(_a							,      lstrip=_a							,      rstrip=_a		) if isinstance(_a							,      _a		) else unk_token
										__lowerCAmelCase											=					AddedToken(_a							,      lstrip=_a							,      rstrip=_a		) if isinstance(_a							,      _a		) else pad_token
										super().__init__(
										    bos_token=_a							,      eos_token=_a							,      unk_token=_a							,      pad_token=_a							,      add_bos_token=_a							,      add_eos_token=_a							,      sp_model_kwargs=self.sp_model_kwargs							,      clean_up_tokenization_spaces=_a							,      legacy=_a							,      **_a							,      )
										if legacy:
																logger.warning_once(
																    F"""You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to"""
																    ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565'''		)
										__lowerCAmelCase											=					legacy
										__lowerCAmelCase											=					vocab_file
										__lowerCAmelCase											=					add_bos_token
										__lowerCAmelCase											=					add_eos_token
										__lowerCAmelCase											=					spm.SentencePieceProcessor(**self.sp_model_kwargs		)
										self.sp_model.Load(_a		)




				def __getstate__(self		):
										__lowerCAmelCase											=					self.__dict__.copy()
										__lowerCAmelCase											=					None
										__lowerCAmelCase											=					self.sp_model.serialized_model_proto()
										return state




				def __setstate__(self							,      __lowercase		):
										__lowerCAmelCase											=					d
										__lowerCAmelCase											=					spm.SentencePieceProcessor(**self.sp_model_kwargs		)
										self.sp_model.LoadFromSerializedProto(self.sp_model_proto		)




				@property
				def        _snake_case	(self		):
										return self.sp_model.get_piece_size()




				def        _snake_case	(self		):
										__lowerCAmelCase											=					{self.convert_ids_to_tokens(_a		): i for i in range(self.vocab_size		)}
										vocab.update(self.added_tokens_encoder		)
										return vocab




				def        _snake_case	(self							,      __lowercase							,      **__lowercase		):
										# Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at
										# the beginning of the text
										if not self.legacy:
																__lowerCAmelCase											=					SPIECE_UNDERLINE + text.replace(_a							,      ''' '''		)
										return super().tokenize(_a							,      **_a		)




				def        _snake_case	(self							,      __lowercase		):
										if not self.legacy:
																__lowerCAmelCase											=					text.startswith(_a		)
																if is_first:
																						__lowerCAmelCase											=					text[1:]

										__lowerCAmelCase											=					self.sp_model.encode(_a							,      out_type=_a		)

										if not self.legacy and not is_first and not text.startswith(''' '''		) and tokens[0].startswith(_a		):
																__lowerCAmelCase											=					([tokens[0][1:]] if len(tokens[0]		) > 1 else []) + tokens[1:]
										return tokens




				def        _snake_case	(self							,      __lowercase		):
										return self.sp_model.piece_to_id(_a		)




				def        _snake_case	(self							,      __lowercase		):
										__lowerCAmelCase											=					self.sp_model.IdToPiece(_a		)
										return token




				def        _snake_case	(self							,      __lowercase		):
										__lowerCAmelCase											=					[]
										__lowerCAmelCase											=					''
										__lowerCAmelCase											=					False
										for i, token in enumerate(_a		):
																# make sure that special tokens are not decoded using sentencepiece model
																if token in self.all_special_tokens:
																						if not prev_is_special and i != 0:
																												out_string += " "
																						out_string += self.sp_model.decode(_a		) + token
																						__lowerCAmelCase											=					True
																						__lowerCAmelCase											=					[]
																else:
																						current_sub_tokens.append(_a		)
																						__lowerCAmelCase											=					False
										out_string += self.sp_model.decode(_a		)
										return out_string




				def        _snake_case	(self							,      __lowercase							,      __lowercase = None		):
										if not os.path.isdir(_a		):
																logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""		)
																return
										__lowerCAmelCase											=					os.path.join(
										    _a							,      (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']		)

										if os.path.abspath(self.vocab_file		) != os.path.abspath(_a		) and os.path.isfile(self.vocab_file		):
																copyfile(self.vocab_file							,      _a		)
										elif not os.path.isfile(self.vocab_file		):
																with open(_a							,      '''wb'''		) as fi:
																						__lowerCAmelCase											=					self.sp_model.serialized_model_proto()
																						fi.write(_a		)

										return (out_vocab_file,)




				def        _snake_case	(self							,      __lowercase							,      __lowercase=None		):
										__lowerCAmelCase											=					[self.bos_token_id] if self.add_bos_token else []
										__lowerCAmelCase											=					[self.eos_token_id] if self.add_eos_token else []

										__lowerCAmelCase											=					bos_token_id + token_ids_a + eos_token_id

										if token_ids_a is not None:
																__lowerCAmelCase											=					output + bos_token_id + token_ids_a + eos_token_id

										return output




				def        _snake_case	(self							,      __lowercase							,      __lowercase = None							,      __lowercase = False		):
										if already_has_special_tokens:
																return super().get_special_tokens_mask(
																    token_ids_a=_a							,      token_ids_a=_a							,      already_has_special_tokens=_a		)

										__lowerCAmelCase											=					[1] if self.add_bos_token else []
										__lowerCAmelCase											=					[1] if self.add_eos_token else []

										if token_ids_a is None:
																return bos_token_id + ([0] * len(_a		)) + eos_token_id
										return (
										    bos_token_id
										    + ([0] * len(_a		))
										    + eos_token_id
										    + bos_token_id
										    + ([0] * len(_a		))
										    + eos_token_id
										)




				def        _snake_case	(self							,      __lowercase							,      __lowercase = None		):
										__lowerCAmelCase											=					[self.bos_token_id] if self.add_bos_token else []
										__lowerCAmelCase											=					[self.eos_token_id] if self.add_eos_token else []

										__lowerCAmelCase											=					[0] * len(bos_token_id + token_ids_a + eos_token_id		)

										if token_ids_a is not None:
																output += [1] * len(bos_token_id + token_ids_a + eos_token_id		)

										return output




				def        _snake_case	(self							,      __lowercase		):
										__lowerCAmelCase											=					list(conversation.iter_texts()		)
										if not all([is_user for is_user, msg in dialogue[::2]]		) or not all(
										    [not is_user for is_user, msg in dialogue[1::2]]		):
																raise ValueError(
																    '''The model only supports \'user\' and \'assistant\' roles, starting with user and alternating (u/a/u/a/u...)'''		)

										__lowerCAmelCase											=					[]
										if len(conversation.past_user_inputs		) > 0:
																if not conversation.past_user_inputs[0].startswith(_a		) or E_SYS not in conversation.past_user_inputs[0]:
																						__lowerCAmelCase											=					(
																						    B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
																						)
										elif not dialogue[0][1].startswith(_a		) or E_SYS not in dialogue[0][1]:
																__lowerCAmelCase											=					(dialogue[0][0], B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + dialogue[0][1])

										dialog_tokens += sum(
										    [
										        [self.bos_token_id]
										        + self.encode(
										            F"""{B_INST} {(prompt[1]).strip()} {E_INST} {(answer[1]).strip()} """							,      add_special_tokens=_a		)
										        + [self.eos_token_id]
										        for prompt, answer in zip(dialogue[::2]							,      dialogue[1::2]		)
										    ]							,      []							,      )
										if not (dialogue[-1][0]):
																raise ValueError(F"""Last message must be from user, got {dialogue[-1]["role"]}"""		)
										dialog_tokens += [self.bos_token_id] + self.encode(
										    F"""{B_INST} {(dialogue[-1][1]).strip()} {E_INST}"""							,      add_special_tokens=_a		)
										return dialog_tokens


'''simple docstring'''




def _UpperCamelCase (							SCREAMING_SNAKE_CASE_ = 1_000				):
     lowercase_       :							Tuple  					=       [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)
     lowercase_       :							List[Any]  					=       [0, 0, 6, 6, 5, 5, 5, 7, 6, 6]

     lowercase_       :							Optional[Any]  					=       0

     for i in range(1	,							n + 1				):
          if i < 1_000:
               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 // 1_000] + 8
     return count


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




