9의 가장 작은 배수, 0에 대한 선택적 실행


22

양의 정수가 주어지면 9의 런 다음에 0의 선택적 런이있는 가장 작은 양의 정수 배수를 찾으십시오. 즉, 정규식과 일치하는 가장 작은 양의 정수 배수를 찾으십시오 /^9+0*$/.

예를 들어, 주어진 양의 정수가 2이면 90은 2의 양의 정수 배수이고 정규식과 일치하는 가장 작은 것이므로 90을 반환합니다 /^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
명확성의 증거?
Destructible Lemon

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코드로 어떻게하지 않았습니까?
Pavel

설명을 추가했습니다.
Dennis



5

자바 스크립트 (ES6), 47 43 42 바이트

@Arnauld 덕분에 -4 바이트 @Luke 덕분에
-1 바이트

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)()됩니다. 에 크롬과 파이어 폭스에서 최대 호출 스택의 크기에 도달 n=7, n=13하고 n=14.


3
1 바이트 더 짧음 :n=>eval('for(i=0;!/^9+0*$/.test(i);)i+=n')
Luke


4

자바 8, 61 57 바이트

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

@JollyJoker 덕분에 -4 바이트 (및 빠른 실행) .

설명:

여기에서 시도하십시오.

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

그래 최적화를 위해! ^^
Olivier Grégoire

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

나는 노력하고 정수와 수학을 시도했지만 이것을 이길 수는 없습니다! 축하합니다 :)
Olivier Grégoire


3

근접 , 16 바이트

;I×≜.ẹḅhᵐc~a₀90∧

온라인으로 사용해보십시오!

꽤 느립니다

설명

;I×≜.              Output = Input × I
    .ẹḅ            Deconcatenate into runs of consecutive equal digits
       hᵐ          Take the head of each run
         c         Concatenate into a number
          ~a₀90∧   That number is a prefix of 90 (i.e. it's 9 or 90)


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의 대답보다 뛰어납니다.

매스 매 티카는이 문제에 관해서이 한 구속의 품질은 사실 StringMatchQ내가 할 수있는, 그래서 전체 일치를 요구 9+0*하기보다는 ^9+0*$.


2
대신 Mathics의 매스 매 티카를 사용하고자하는 경우, 당신과 함께 몇 바이트를 저장할 수 있습니다 "9"..~~"0"...대신 RegularExpression@"9+0*".
나무가 아님

1
@Notatree 덕분에 나중에 염두에 두 겠지만 Mathics를 고수하겠습니다. 나는 이해하지 못하는 구문을 사용하지 않는 것을 선호하며, 그런 구문을 처음 본 것입니다.
Pavel

충분합니다. (Mathematica의 패턴 일치 구문은 강력한 도구이지만 정규식에 익숙하다면 이미 알고 계실 것입니다!)
Tree not

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

Mathematica, 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
Pavel

당신의 명백한 해결책은 17를 할 수 없습니다 ;-)
J42161217


그건 그렇고, 당신의 솔루션은 Mathics에서 작동하며, 그것을 그것으로 바꾸고 TIO 링크를 추가 할 수 있습니다.
Pavel


2

하스켈 , 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 작동 할 수 있다는 사실을 사용 b하여 약간 더 짧은 "잘못된"순서로 s 를 생성 할 수 있습니다 .


1

루비 , 38 + 1 = 39 바이트

-p플래그를 사용합니다 .

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

-p 다음과 같이 프로그램을 둘러 쌉니다.

while gets
    ...
end
puts $_

gets결과를에 저장합니다 $_. eval보다 짧은 숫자로 변환하는 .to_i데 사용되며, 정규 표현식과 일치 할 때까지 $ _ 씩 증가하는 무차별 대입이 사용됩니다. "#{}"sttring interpolation, 주위에 parantheses .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;
}

온라인으로 해보십시오!


더 나은 골프 : [](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;}}94 바이트가 필요합니다. 기본적으로 바이트를 저장하고 불필요한 괄호를 저장하고 람다 함수를 사용하여 유형 명명 및 유형을 저장하는 함수 작업으로 처리하십시오.
enedil

람다를 사용하여 컴파일 할 수 없습니다. 손 좀 줄래?
koita_pisw_sou

내가 끝에 너무 많은 괄호를 넣은 이유 일 수 있습니다.
enedil

또한 람다는 일반 함수에 래핑하는 데 97 바이트가 걸리더라도 전역 범위에 존재하지 않았을 것입니다.
enedil

1

파이썬 2 , 79 바이트

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

온라인으로 사용해보십시오!

일부 설명 이 형태의 작은 자연의 발견 10**n-10**bn>b>=0그 분할 입력합니다.

일부 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

스위프트 3.0, 바이트 : 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}

온라인으로 사용해보십시오!


무엇을 let r=합니까? r다른 곳에서는 언급 되지 않았습니다
Cyoce

@Cyoce let r =은 n.range가 nil 값을 반환하는지 여부를 확인합니다. let _ =를 사용할 수 있습니다. 바이트를 줄이기 위해 여기에서 선택적 바인딩을 사용하고 있습니다.
A. Pooja

1

파이썬 3 , 62 바이트

이 함수는 정수를 취해 0으로 n초기화 m합니다. 그런 다음 끝에서 모든 0을 제거 m하고 결과에 9가 포함되어 있는지 확인하여 그 결과를 반환 m합니다. 그렇지 않은 경우는 추가 nm하고 다시 검사 등

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

온라인으로 사용해보십시오!


1

Java (OpenJDK 8) , 66 바이트, 17시에 질식하지 않음

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

온라인으로 사용해보십시오!

@KevinCruijssen의 솔루션 보다 길지만 약간 더 큰 숫자를 처리 할 수 ​​있습니다. 10 ^ 6-10 ^ 3 = 999000과 같은 후보 숫자를 계산합니다. 64 비트 길이는 여전히 한계이며 n = 23을 초과합니다.

아마 약간 골프를 칠 수는 있지만 이미 작동 시키기에는 너무 오래 걸렸습니다 ...


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}

설명 : 여기서 유일한 마법은 커스텀 반복자 (M'ma 감각이 아닌 CS 의미의 "반복자")입니다.

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

전역 변수 x, 선행 "9" y수, 후행 "0" d수 및 총 자릿수에 작용합니다. 우리는 자릿수를 반복하고 각 자릿수를 선택할 때마다 가장 높은 "0"과 가장 작은 "9"로 시작합니다. 따라서 코드가 수행하는 첫 번째 작업은 d1 로 초기화 되어 1 xy0으로 강제 설정 됩니다. 사용자 정의 반복기는 "0"문자열을 단축 할 수 있는지 확인합니다. 그렇다면 "0"문자열을 하나씩 줄이고 "1"문자열을 하나씩 증가시킵니다. 그렇지 않은 경우 자릿수를 늘리고 "0"수를 자릿수보다 1만큼 작게 설정하고 "9"수를 1로 설정합니다.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.

이것은 최대 16 개까지 작동합니다. 17은 remainder(최대 9999999999999 (13 nines)의 배당 만 허용 할 수 있고 17은 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 바이트

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

설명

{        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 바이트

#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);}

온라인으로 사용해보십시오!

일부 설명 이 형태의 작은 자연의 발견 10**n-10**bn>b>=0그 분할 입력합니다.

일부 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

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.