Найменший кратний запуск 9 з наступним необов'язковим запуском 0


22

З огляду на додатне ціле число, знайдіть його найменший кратне додатне ціле число, яке є пробігом 9, а потім необов'язковий запуск 0. Іншими словами, знайдіть його найменше множинне додатне ціле число, яке узгоджується з регулярним виразом /^9+0*$/.

Наприклад, якщо дане додатне ціле число дорівнює 2, то повертаємо 90, оскільки 90 - це додатне ціле число, кратне 2, і є найменшим, яке відповідає регулярним виразом /^9+0*$/.

Тестові приклади:

n  f(n)
1  9
2  90
3  9
4  900
5  90
6  90
7  999999
8  9000
9  9
10 90
11 99
12 900
13 999999
14 9999990
15 90
16 90000

Це . Найкоротша відповідь у байтах виграє. Застосовуються стандартні лазівки .


3
підтвердження чіткості?
Руйнуючий лимон

2
@DestructibleLemon Цього доказу достатньо, оскільки результат можна помножити на 9.
xnor

1
Я думаю, що більше тестових випадків було б добре перевірити, чи потрібно, щоб рішення вирішили, що 9-й повинен бути перед 0-ми.
xnor

2
@LeakyNun, можливо, ні, але 9900099 є, і його не можна допускати відповідно до правил.
DrQuarius

2
@koita_pisw_sou правило полягає в тому, що програма повинна "теоретично" працювати для будь-якого цілого числа, заданого довільною точністю, пам'яттю та часом.
Leaky Nun

Відповіді:


6

Желе , 13 11 байт

ṚḌ‘DS=ḍ@ð1#

Спробуйте в Інтернеті!

Як це працює

ṚḌ‘DS=ḍ@ð1#  Main link. Argument: n

        ð    Start a dyadic chain with arguments n and n.
         1#  Execute the chain to the left with left argument k = n, n+1, n+2, ...
             and right argument n until 1 match has been found. Return the match.
Ṛ                Get the decimal digits of k, reversed.
 Ḍ               Convert from base 10 to integer.
                 This essentially removes trailing zeroes. As a side effect, it
                 reverses the digits, which doesn't matter to us.
  ‘              Increment the resulting integer. If and only if it consisted
                 entirely of 9's, the result is a power of 10.
   DS            Compute the sum of the digits. The sum is 1 if and only if the
                 integer is a power of 10. Note that the sum cannot be 0.
      ḍ@         Test k for divisibility by n.
     =           Compare the results.

4
ಠ_ಠ , як ви робили це з ні 9або 0в вашому коді
Павла

Я додав пояснення.
Денніс



5

JavaScript (ES6), 47 43 42 байт

-4 байти завдяки @Arnauld
-1 байт завдяки @Luke

n=>eval('for(i=0;!/^9+0*$/.test(i);)i+=n')

Тести

let f=
n=>eval('for(i=0;!/^9+0*$/.test(i);)i+=n')

for(let i=1;i<=16;i++)console.log(`f(${i}) = `+f(i))

Рекурсивний розчин (не вдається для 7, 13 і 14), 38 байт

n=>g=(i=0)=>/^9+0*$/.test(i+=n)?i:g(i)

Називається як f(5)(). Досягає максимальний розмір стека викликів в Chrome і Firefox для n=7, n=13і n=14.


3
На один байт коротше:n=>eval('for(i=0;!/^9+0*$/.test(i);)i+=n')
Лука

4

Рубін , 36 байт

->x{r=0;1until"#{r+=x}"=~/^9+0*$/;r}

Брут-форсинг - вічно займає х = 17.

Спробуйте в Інтернеті!


Я придумав майже те саме рішення, що і ви, але як повну програму: codegolf.stackexchange.com/a/130106/60042 . Я запозичив використання строкової інтерполяції у вас, сподіваюся, це нормально.
Павло

4

Java 8, 61 57 байт

n->{int r=0;for(;!(""+r).matches("9+0*");r+=n);return r;}

-4 байти (і швидше виконання) завдяки @JollyJoker .

Пояснення:

Спробуйте тут.

n->{                              // Method with integer as parameter and return-type
  int r=0;                        //  Result-integer
  for(;!(""+r).matches("9+0*");   //  Loop as long as `r` doesn't match the regex
    r+=n                          //   And increase `r` by the input every iteration
  );                              //  End of loop
  return r;                       //  Return the result-integer
}                                 // End of method

Так для оптимізації! ^^
Олів'є Грегоар

1
Зростання на n дозволяє уникнути r%nперевірки,n->{int r=0;for(;!(""+(r+=n)).matches("9+0*"););return r;}
JollyJoker

for(;!(""+r).matches("9+0*");r+=n)
JollyJoker

Я пробував, і намагався займатися цілими числами та математикою, але не можу це перемогти! Поздравляю :)
Олів'є Грегоар




2

RProgN 2 , 18 байт

x={x*'^9+0*$'E}éx*

Пояснив

x={x*'^9+0*$'E}éx*
x=                  # Set the value of "x" to the input.
  {           }é    # Find the first positive integer in which passing it to the defined function returns truthy.
   x*               # Multiply the index by x, this essentially searches multiples now.
     '^9+0*$'       # A Regex defined by a literal string.
             E      # Does the multiple match the regex?
                x*  # Multiple the outputted index by x, giving the result.

Спробуйте в Інтернеті!


2

Математика , 71 байт

(x=#;While[!StringMatchQ[ToString@x,RegularExpression@"9+0*"],x+=#];x)&

Спробуйте в Інтернеті!

Не дуже цікаве рішення грубої сили, але воно перемагає іншу відповідь Mathematica, в якій використовуються деякі хитрі хитрощі.

Єдиним, що викуповує якість Mathematica щодо цього виклику, є той факт, що StringMatchQвимагає повного матчу, тому я можу зробити це, 9+0*а не ніж ^9+0*$.


2
Якщо ви бажаєте використовувати Mathematica замість Mathics, ви можете зберегти кілька байтів, "9"..~~"0"...а не RegularExpression@"9+0*".
Не дерево

1
@Notatree спасибі, я буду пам'ятати про це на наступний час, але я буду дотримуватися Mathics. Я вважаю за краще не використовувати синтаксис, якого я не розумію, і це перший раз, коли я бачив такий синтаксис.
Павло

Досить справедливо. (Синтаксис відповідності шаблону Mathematica - це потужний інструмент, але якщо ви знайомі з регулярними виразами, ви, напевно, це вже знаєте!)
Не дерево

2

Пакет, 175 байт

@set/pn=
@set s=
:g
@set/ag=-~!(n%%2)*(!(n%%5)*4+1)
@if not %g%==1 set s=0%s%&set/an/=g&goto g
@set r=1
:r
@set s=9%s%
@set/ar=r*10%%n
@if %r% gtr 1 goto r
@echo %s%

Здійснює введення даних STDIN. Це не грубе рішення, але насправді засноване на моїй відповіді на Фракцію до точної десяткової, тому воно буде працювати для 17, 19 і т.д., що в іншому випадку в будь-якому випадку перевищить його ціле обмеження.


2

Математика, 127 байт

Select[FromDigits/@Select[Tuples[{0,9},c=#],Count[#,9]==1||Union@Differences@Flatten@Position[#,9]=={1}&],IntegerQ[#/c]&][[1]]&


Вхідні дані

[17]

Вихідні дані

9999999999999999

ось перші 20 термінів

{9, 90, 9, 900, 90, 90, 999999, 9000, 9, 90, 99, 900, 999999, 9999990, 90, 90000, 9999999999999999, 90, 999999999999999999, 900}


1
Розумне, але очевидне рішення здається найкоротшим: codegolf.stackexchange.com/a/130115/60042
Павло

ваше очевидне рішення не може зробити 17 ;-)
J42161217

Що я можу сказати, не найшвидший код
Павло

До речі, ваше рішення працює в Mathics, ви можете змінити його на це і додати TIO-посилання.
Павло


2

Haskell , 53 байти

f приймає і повертає ціле число.

f n=filter(all(<'1').snd.span(>'8').show)[n,n+n..]!!0

Спробуйте в Інтернеті!

Цього разу йде 17, що зручно лише поза тестовими випадками. Більш швидка версія в 56 байт:

f n=[x|a<-[1..],b<-[0..a-1],x<-[10^a-10^b],mod x n<1]!!0

Спробуйте в Інтернеті!

Як це працює

  • fгенерує всі кратні n, перетворює кожну в рядок, фільтрує ті, що мають правильний формат, а потім бере перший.

  • Чим швидше версія натомість використовує , що необхідні номери мають вигляд 10^a-10^b, a>=1, a>b>=0. Для цілей гольфу він також використовує той факт, що для мінімальних може працювати aлише один b , що дозволяє йому генерувати bs у трохи коротшому "неправильному" порядку.


1

Ruby , 38 + 1 = 39 байт

Використовує -pпрапор.

$_=y=eval$_
1until"#{$_+=y}"=~/^9+0*$/

-p оточує програму:

while gets
    ...
end
puts $_

getsзберігає свій результат у $_. evalвикористовується для перетворення його в число, оскільки воно коротше ніж .to_i, тоді застосовується груба сила, збільшуючи $ _, поки вона не відповідає регексу. "#{}"- це інтерполяція штрихування, вона коротша, ніж .to_sдзвінок, оскільки для цього знадобиться парантез навколо $_+=y. Нарешті,$_ друкується.

Спробуйте в Інтернеті!

Спробуйте всі тестові випадки!



1

C ++, 106 байт

int main(){long N,T=9,j=10,M;cin>>N;while(T%N){if(T/j){T+=(M/j);j*=10;}else{T=(T+1)*9;j=10;M=T;}}cout<<T;}

Детальна форма:

int main()
{
    long N,T=9,j=10,M;
    cin >> N;

    while (T%N)
    {
        if (T/j)
        {
            T += (M/j);
            j *= 10;
        }
        else
        {
            T = (T+1)*9;
            j = 10;
            M = T;
        }
    } 

    cout << T;
}

Спробуйте його онлайн!


Better golfed: [](int n){int T=9,j=10,m;while(t%n)if(t/j){t+=m/j;j*=10;}else{t=(t+1)*9;j=10;m=t;}return t;}}, takes 94 bytes. Essentially, treat it as a function task to save bytes, save up on unneeded parentheses, use lambda function to save on type naming and type.
enedil

can't make it compile using lambda. could u give a hand?
koita_pisw_sou

It may be the reason that I put too amuch parentheses on the end.
enedil

In addition, lambda probably has not to exist in global scope, even though wrapping it into regular function takes 97 bytes.
enedil

1

Python 2, 79 bytes

x=input();n=10;y=9
while y%x:
 b=n
 while(b-1)*(y%x):b/=10;y=n-b
 n*=10
print y

Try it online!

Some explanations It finds the smallest natural of form 10**n-10**b with n>b>=0 that divides the input.

Some IO

f(1) = 9
f(2) = 90
f(3) = 9
f(4) = 900
f(5) = 90
f(6) = 90
f(7) = 999999
f(8) = 9000
f(9) = 9
f(10) = 90
f(11) = 99
f(12) = 900
f(13) = 999999
f(14) = 9999990
f(15) = 90
f(16) = 90000
f(17) = 9999999999999999
f(18) = 90
f(19) = 999999999999999999


1

Swift 3.0, Bytes:121

var i=2,m=1,n=""
while(i>0){n=String(i*m)
if let r=n.range(of:"^9+0*$",options:.regularExpression){print(n)
break};m=m+1}

Try it online!


What does let r= do? I don't see r referred to anywhere else
Cyoce

@Cyoce let r= checks whether the n.range returns value nil or not.You can use let _=.I am using optional binding here to reduce no of bytes.
A. Pooja

1

Python 3, 62 bytes

This function takes an integer n and initializes m to zero. Then it removes all zeros from the ends of m and checks if the result only contains 9's, returning m if it does. If not, it adds n to m and checks again, etc.

def f(n,m=0):
 while{*str(m).strip('0')}!={'9'}:m+=n
 return m

Try it online!


1

Java (OpenJDK 8), 66 bytes, doesn't choke on 17

n->{long a=10,b=1;for(;(a-b)%n>0;b=(b<10?a*=10:b)/10);return a-b;}

Try it online!

Longer than @KevinCruijssen's solution but can handle slightly larger numbers. It calculates the candidate numbers like 10^6 - 10^3 = 999000. 64-bit longs are still the limit, breaking for n=23.

Can probably be golfed a bit but already took too long to make it work...


1

><>, 35 bytes

&a:v ;n-<
:,a/?(1:^!?%&:&-}:{
a*:\~

Try it online, or watch it at the fish playground!

Assumes the input is already on the stack. Works by looking for numbers of the form 10a − 10b, with a < b (yes, that's a less than sign — it takes fewer bytes!) until that's divisible by the input, then printing 10b − 10a. This is much faster than the brute force method (which would be difficult in ><> anyway).


1

V, 19 14 bytes

é0òÀ/[1-8]ü09

Try it online!

Explanation

é0              ' <m-i>nsert a 0
  ò             ' <m-r>ecursively
   À            ' <m-@>rgument times
               ' <C-A> increment the number (eventually gives all multiples)
     /[1-8]ü09  ' find ([1-8]|09) if this errors, the number is of the form
                ' (9+0*) (because there won't ever be just zeros)
                ' implicitly end the recursion which breaks on the above error

1

JavaScript (ES6), 51 49 bytes

let
f=(n,x=1,y=1)=>(x-y)%n?f(n,x,y*10):x-y||f(n,x*10)
<input type=number value=1 step=1 min=1 oninput=O.value=f(value)>
<input type=number value=9 id=O disabled>

Not the shortest approach, but it is wicked fast.


1

Mathematica, 82 bytes

Using the pattern of submission from @Jenny_mathy 's answer...

(d=x=1;y=0;f:=(10^x-1)10^y;n:=If[y>0,y--;x++,y=d;d++;x=1];While[Mod[f,#]!=0,n];f)&

Input:

[17]

Output:

9999999999999999

And relative to the argument in comments at @Jenny_mathy's answer with @Phoenix ... RepeatedTiming[] of application to the input [17] gives

{0.000518, 9999999999999999}

so half a millisecond. Going to a slightly larger input, [2003] :

{3.78, 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999}

a bit under 4 seconds.

Test table: On the first 30 positive integers, the results are

{9, 90, 9, 900, 90, 90, 999999, 9000, 9, 90, 99, 900, 999999, 
9999990, 90, 90000, 9999999999999999, 90, 999999999999999999, 900, 
999999, 990, 9999999999999999999999, 9000, 900, 9999990, 999, 
99999900, 9999999999999999999999999999, 90}

Explanation: The only magic here is the custom iterator ("iterator" in the CS sense, not the M'ma sense)

n := If[ y>0  ,  y-- ; x++  ,  y=d ; d++ ; x=1]

which acts on the global variables x, the number of leading "9"s, y, the number of trailing "0"s, and d, the total number of digits. We wish to iterate through the number of digits, and, for each choice of number of digits, start with the most "0"s and the least "9"s. Thus the first thing the code does is initialize d to 1, forcing x to 1 and y to 0. The custom iterator checks that the string of "0"s can be shortened. If so, it shortens the string of "0"s by one and increases the string of "1"s by one. If not, it increments the number of digits, sets the number of "0"s to one less than the number of digits, and sets the number of "9"s to 1. (This is actually done in a slightly different order to shave a few characters, since the old value of d is the desired value of y.)


And yet, still longer than brute force and regex.
Pavel

@Phoenix : So what's your timing on 2003?
Eric Towers

1

Ti-Basic (TI-84 Plus CE), 48 41 bytes

Prompt X
For(K,1,0
For(M,-K+1,0
10^(K)-10^(-M
If 0=remainder(Ans,X
Return
End
End

Input is Prompt-ed during the program; output is stored in Ans.

Explanation:

Tries numbers of the form (10n)(10m-1) = 10k-10m, where m+n=k starts at 1 and increases, and for each value of k, it tries m=1,n=k-1; m=2,n=k-2; ... m=k,n=0; until it finds a multiple of X.

This works up to 16; 17 gives a domain error because remainder( can only accept dividends up to 9999999999999 (13 nines), and 17 should output 9999999999999999 (16 nines).

Prompt X               # 3 bytes, input number
For(K,1,0              # 7 bytes, k in the description above; until a match is found
For(M,-K+1,0           # 10 bytes, start with n=1, m=(k-n)=k-1;
                           # then n=2, m=(k-n)=k-2, up to n=k, m=(k-n)=0
                           # (M=-m because it saved one byte)
10^(K)-10^(-M           # 8 bytes, n=(k-m) nines followed by m zeroes → Ans
If not(remainder(Ans,X # 8 bytes, If X is a factor of Ans (remainder = 0)
Return                 # 2 bytes, End program, with Ans still there
End                    # 2 bytes,
End                    # 1 byte (no newline)

1

QBIC, 53 bytes

{p=p+1┘o=p*9_F!o$|┘n=!A!~(_l!n$|=_l!n+1$|)-(o%:)|\_Xo

Explanation

{        infinitely DO
p=p+1    raise p (starts out as 0)
┘o=p*9   Get the mext multiple of 9 off of p
_F!o$|   Flip a string representation of p*9
┘n=!A!   and set 'n' to be an int version of the flipped p*9 
         (this effectively drops trailing 0's)
~        This IF will subtract two values: the first is either 0 for n=x^10, or -1
         and the second bit does (p*9) modulo 'a' (input number): also 0 for the numbers we want
(
 _l!n$|  the length of n's string representation
=        is equal to
_l!n+1$| the length of (n+1)'s string rep (81 + 1 = 82, both are 2 long; 99 + 1 = 100, there's a difference)
)        The above yields -1 (Qbasic's TRUE value) for non-9 runs, 0 for n=x^10
-        Subtract from that 
(o%:)    (p*9) modulo a     0 for p*9 = a*y
|       THEN (do nothing, since we want 0+0=0 in the conditionals above, execution of the right path jumps to ELSE
\_Xo    ELSE quit, printing (p*9)

1

C (gcc), 126 bytes

#include<stdio.h>
main(x,n,y,b){n=10;y=9;scanf("%d",&x);while(y%x){b=n;while((b-1)*(y%x)){b/=10;y=n-b;}n*=10;}printf("%d",y);}

Try it online!

Some explanations It finds the smallest natural of form 10**n-10**b with n>b>=0 that divides the input.

Some IO

f(1) = 9
f(2) = 90
f(3) = 9
f(4) = 900
f(5) = 90
f(6) = 90
f(7) = 999999
f(8) = 9000
f(9) = 9
f(10) = 90
f(11) = 99
f(12) = 900
f(13) = 999999
f(14) = 9999990
f(15) = 90
f(16) = 90000

1

Perl 5, 23 + 2 (-pa) = 25 bytes

Brute Force Method

$_+=$F[0]while!/^9+0*$/

Try it online!

It's slow, but it's tiny.

More Efficient Method:

41 + 2 (-pa) = 43 bytes

$_=9;s/0/9/||($_=9 .y/9/0/r)while$_%$F[0]

Try it online!

It works well for any input, but it's longer code.

Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.