





UpperCamelCase__   : List[Any]					  = range(2, 20 + 1)
UpperCamelCase__   : Optional[Any]					  = [10**k for k in range(ks[-1] + 1)]
UpperCamelCase__   : Any					  = {}




def    A_(			A				,      A				,      A				,      A   ):
 UpperCAmelCase_								=     sum(a_i[j] for j in range(A				,      len(A   )   )   )
 UpperCAmelCase_								=     sum(a_i[j] * base[j] for j in range(min(len(A   )				,      A   )   )   )

 UpperCAmelCase_								=     0, 0
 UpperCAmelCase_								=     n - i

 UpperCAmelCase_								=     memo.get(A   )

 if sub_memo is not None:
  UpperCAmelCase_								=     sub_memo.get(A   )

  if jumps is not None and len(A   ) > 0:
   # find and make the largest jump without going over
   UpperCAmelCase_								=     -1
   for _k in range(len(A   ) - 1				,      -1				,      -1   ):
    if jumps[_k][2] <= k and jumps[_k][1] <= max_dn:
     UpperCAmelCase_								=     _k
     break

   if max_jump >= 0:
    UpperCAmelCase_								=     jumps[max_jump]
    # since the difference between jumps is cached, add c
    UpperCAmelCase_								=     diff + c
    for j in range(min(A				,      len(A   )   )   ):
     UpperCAmelCase_								=     divmod(A				,      10   )
    if new_c > 0:
     add(A				,      A				,      A   )

  else:
   UpperCAmelCase_								=     []
 else:
  UpperCAmelCase_								=     {c: []}
  UpperCAmelCase_								=     sub_memo

 if dn >= max_dn or c + diff >= base[k]:
  return diff, dn

 if k > ks[0]:
  while True:
   # keep doing smaller jumps
   UpperCAmelCase_								=     next_term(A				,      k - 1				,      i + dn				,      A   )
   diff += _diff
   dn += terms_jumped

   if dn >= max_dn or c + diff >= base[k]:
    break
 else:
  # would be too small a jump, just compute sequential terms instead
  UpperCAmelCase_								=     compute(A				,      A				,      i + dn				,      A   )
  diff += _diff
  dn += terms_jumped

 UpperCAmelCase_								=     sub_memo[c]

 # keep jumps sorted by # of terms skipped
 UpperCAmelCase_								=     0
 while j < len(A   ):
  if jumps[j][1] > dn:
   break
  j += 1

 # cache the jump for this value digitsum(b) and c
 sub_memo[c].insert(A				,      (diff, dn, k)   )
 return (diff, dn)




def    A_(			A				,      A				,      A				,      A   ):
 if i >= n:
  return 0, i
 if k > len(A   ):
  a_i.extend([0 for _ in range(k - len(A   )   )]   )

 # note: a_i -> b * 10^k + c
 # ds_b -> digitsum(b)
 # ds_c -> digitsum(c)
 UpperCAmelCase_								=     i
 UpperCAmelCase_								=     0, 0, 0
 for j in range(len(A   )   ):
  if j >= k:
   ds_b += a_i[j]
  else:
   ds_c += a_i[j]

 while i < n:
  i += 1
  UpperCAmelCase_								=     ds_c + ds_b
  diff += addend
  UpperCAmelCase_								=     0
  for j in range(A   ):
   UpperCAmelCase_								=     a_i[j] + addend
   UpperCAmelCase_								=     divmod(A				,      10   )

   ds_c += a_i[j]

  if addend > 0:
   break

 if addend > 0:
  add(A				,      A				,      A   )
 return diff, i - start_i




def    A_(			A				,      A				,      A   ):
 for j in range(A				,      len(A   )   ):
  UpperCAmelCase_								=     digits[j] + addend
  if s >= 10:
   UpperCAmelCase_								=     divmod(A				,      10   )
   UpperCAmelCase_								=     addend // 10 + quotient
  else:
   UpperCAmelCase_								=     s
   UpperCAmelCase_								=     addend // 10

  if addend == 0:
   break

 while addend > 0:
  UpperCAmelCase_								=     divmod(A				,      10   )
  digits.append(A   )




def    A_(			A = 10**15   ):
 UpperCAmelCase_								=     [1]
 UpperCAmelCase_								=     1
 UpperCAmelCase_								=     0
 while True:
  UpperCAmelCase_								=     next_term(A				,      20				,      i + dn				,      A   )
  dn += terms_jumped
  if dn == n - i:
   break

 UpperCAmelCase_								=     0
 for j in range(len(A   )   ):
  a_n += digits[j] * 10**j
 return a_n


if __name__ == "__main__":
    print(f"{solution() = }")









import inspect
import unittest

from huggingface_hub import hf_hub_download

from transformers import ASTConfig
from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_torchaudio_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch
				from torch import nn

				from transformers import ASTForAudioClassification, ASTModel
				from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import (
				    AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
				)


if is_torchaudio_available():
				import torchaudio

				from transformers import ASTFeatureExtractor







class   _UpperCamelCase  :







					'''simple docstring'''

					def __init__(						self    :  Optional[int] ,					__lowercase    :  Union[str, Any] ,					__lowercase    :  Optional[int]=13 ,					__lowercase    :  Union[str, Any]=2 ,					__lowercase    :  Union[str, Any]=24 ,					__lowercase    :  Tuple=16 ,					__lowercase    :  Any=True ,					__lowercase    :  List[str]=True ,					__lowercase    :  List[Any]=32 ,					__lowercase    :  Tuple=5 ,					__lowercase    :  List[str]=4 ,					__lowercase    :  Optional[Any]=37 ,					__lowercase    :  Tuple="gelu" ,					__lowercase    :  Any=0.1 ,					__lowercase    :  Optional[int]=0.1 ,					__lowercase    :  Tuple=10 ,					__lowercase    :  List[str]=0.02 ,					__lowercase    :  str=None ,					__lowercase    :  Any=2 ,					__lowercase    :  Optional[int]=2 ,					):






						'''simple docstring'''







						UpperCAmelCase_								=     parent
						UpperCAmelCase_								=     batch_size
						UpperCAmelCase_								=     patch_size
						UpperCAmelCase_								=     max_length
						UpperCAmelCase_								=     num_mel_bins
						UpperCAmelCase_								=     is_training
						UpperCAmelCase_								=     use_labels
						UpperCAmelCase_								=     hidden_size
						UpperCAmelCase_								=     num_hidden_layers
						UpperCAmelCase_								=     num_attention_heads
						UpperCAmelCase_								=     intermediate_size
						UpperCAmelCase_								=     hidden_act
						UpperCAmelCase_								=     hidden_dropout_prob
						UpperCAmelCase_								=     attention_probs_dropout_prob
						UpperCAmelCase_								=     type_sequence_label_size
						UpperCAmelCase_								=     initializer_range
						UpperCAmelCase_								=     scope
						UpperCAmelCase_								=     frequency_stride
						UpperCAmelCase_								=     time_stride

						# in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
						UpperCAmelCase_								=     (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
						UpperCAmelCase_								=     (self.max_length - self.patch_size) // self.time_stride + 1
						UpperCAmelCase_								=     frequency_out_dimension * time_out_dimension
						UpperCAmelCase_								=     num_patches + 2





					def        SCREAMING_SNAKE_CASE							(						self    :  int		):






						'''simple docstring'''







						UpperCAmelCase_								=     floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]		)

						UpperCAmelCase_								=     None
						if self.use_labels:
							UpperCAmelCase_								=     ids_tensor([self.batch_size] ,					self.type_sequence_label_size		)

						UpperCAmelCase_								=     self.get_config()

						return config, input_values, labels





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						return ASTConfig(
						    patch_size=self.patch_size ,					max_length=self.max_length ,					num_mel_bins=self.num_mel_bins ,					hidden_size=self.hidden_size ,					num_hidden_layers=self.num_hidden_layers ,					num_attention_heads=self.num_attention_heads ,					intermediate_size=self.intermediate_size ,					hidden_act=self.hidden_act ,					hidden_dropout_prob=self.hidden_dropout_prob ,					attention_probs_dropout_prob=self.attention_probs_dropout_prob ,					is_decoder=__lowercase ,					initializer_range=self.initializer_range ,					frequency_stride=self.frequency_stride ,					time_stride=self.time_stride ,					)





					def        SCREAMING_SNAKE_CASE							(						self    :  List[str] ,					__lowercase    :  int ,					__lowercase    :  Dict ,					__lowercase    :  Optional[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     ASTModel(config=__lowercase		)
						model.to(__lowercase		)
						model.eval()
						UpperCAmelCase_								=     model(__lowercase		)
						self.parent.assertEqual(result.last_hidden_state.shape ,					(self.batch_size, self.seq_length, self.hidden_size)		)





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.prepare_config_and_inputs()
						(
						    (
						    UpperCAmelCase_
						)						,	(
						    UpperCAmelCase_
						)						,	(
						    UpperCAmelCase_
						)						,	
						)								=     config_and_inputs
						UpperCAmelCase_								=     {"""input_values""": input_values}
						return config, inputs_dict







@require_torch
class   _UpperCamelCase  (       A_						,       A_						,       unittest.TestCase  ):







					'''simple docstring'''

					lowerCamelCase     :     Any			    =       (
					    (
					        ASTModel,
					        ASTForAudioClassification,
					    )
					    if is_torch_available()
					    else ()
					)
					lowerCamelCase     :     Optional[Any]			    =       (
					    {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
					    if is_torch_available()
					    else {}
					)
					lowerCamelCase     :     Union[str, Any]			    =       False
					lowerCamelCase     :     Tuple			    =       False
					lowerCamelCase     :     List[str]			    =       False
					lowerCamelCase     :     List[Any]			    =       False





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any] ,					__lowercase    :  Union[str, Any] ,					__lowercase    :  List[str] ,					__lowercase    :  int ,					__lowercase    :  str ,					__lowercase    :  Dict		):






						'''simple docstring'''







						if pipeline_test_casse_name == "AudioClassificationPipelineTests":
							return True

						return False





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     ASTModelTester(self		)
						UpperCAmelCase_								=     ConfigTester(self ,					config_class=__lowercase ,					has_text_modality=__lowercase ,					hidden_size=37		)





					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







						self.config_tester.run_common_tests()





					@unittest.skip(reason="""AST does not use inputs_embeds"""		)
					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[Any]		):






						'''simple docstring'''







						pass





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_						,	UpperCAmelCase_								=     self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							UpperCAmelCase_								=     model_class(__lowercase		)
							self.assertIsInstance(model.get_input_embeddings() ,					(nn.Module)		)
							UpperCAmelCase_								=     model.get_output_embeddings()
							self.assertTrue(x is None or isinstance(__lowercase ,					nn.Linear		)		)





					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[Any]		):






						'''simple docstring'''







						UpperCAmelCase_						,	UpperCAmelCase_								=     self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							UpperCAmelCase_								=     model_class(__lowercase		)
							UpperCAmelCase_								=     inspect.signature(model.forward		)
							# signature.parameters is an OrderedDict => so arg_names order is deterministic
							UpperCAmelCase_								=     [*signature.parameters.keys()]

							UpperCAmelCase_								=     ["""input_values"""]
							self.assertListEqual(arg_names[:1] ,					__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__lowercase		)





					@slow
					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







						for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							UpperCAmelCase_								=     ASTModel.from_pretrained(__lowercase		)
							self.assertIsNotNone(__lowercase		)




def    A_(			):
	UpperCAmelCase_								=     hf_hub_download(
	    repo_id="""nielsr/audio-spectogram-transformer-checkpoint"""				,      filename="""sample_audio.flac"""				,      repo_type="""dataset"""   )

	UpperCAmelCase_						,	UpperCAmelCase_								=     torchaudio.load(A   )

	return audio, sampling_rate







@require_torch
@require_torchaudio
class   _UpperCamelCase  (       unittest.TestCase  ):







					'''simple docstring'''

					@cached_property
					def        SCREAMING_SNAKE_CASE							(						self    :  Any		):






						'''simple docstring'''







						return (
						    ASTFeatureExtractor.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593"""		)
						    if is_torchaudio_available()
						    else None
						)





					@slow
					def        SCREAMING_SNAKE_CASE							(						self    :  Any		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.default_feature_extractor
						UpperCAmelCase_								=     ASTForAudioClassification.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593"""		).to(__lowercase		)

						UpperCAmelCase_								=     self.default_feature_extractor
						UpperCAmelCase_						,	UpperCAmelCase_								=     prepare_audio()
						UpperCAmelCase_								=     audio.squeeze().numpy()
						UpperCAmelCase_								=     feature_extractor(__lowercase ,					sampling_rate=__lowercase ,					return_tensors="""pt"""		).to(__lowercase		)

						# forward pass
						with torch.no_grad():
							UpperCAmelCase_								=     model(**__lowercase		)

						# verify the logits
						UpperCAmelCase_								=     torch.Size((1, 5_27)		)
						self.assertEqual(outputs.logits.shape ,					__lowercase		)

						UpperCAmelCase_								=     torch.tensor([-0.8760, -7.0042, -8.6602]		).to(__lowercase		)

						self.assertTrue(torch.allclose(outputs.logits[0, :3] ,					__lowercase ,					atol=1e-4		)		)


