Residu palindromik


25

Hari ini, saat saya menulis ini, adalah 31 Maret. Di AS, ini 3/31. Saya bermain-main dengan 331sebagai nomor untuk datang dengan tantangan, dan menemukan bahwa residu (modulo angka kecil) adalah palindromik. 331%2=1, 331%3=1, 331%4=3, 331%5=1, 331%6=1( 11311).

Tantangan Anda di sini adalah, ketika diberi bilangan bulat n > 2, output nangka positif pertama yang memiliki residu palindromik ketika diambil modulo [2,n].

Misalnya, untuk input 7, output harus 1, 42, 43, 140, 182, 420, 421. Inilah bagan yang menjelaskan mengapa demikian:

        mod
num | 2 3 4 5 6 7
-----------------
  1 | 1 1 1 1 1 1
 42 | 0 0 2 2 0 0
 43 | 1 1 3 3 1 1
140 | 0 2 0 0 2 0
182 | 0 2 2 2 2 0
420 | 0 0 0 0 0 0
421 | 1 1 1 1 1 1

Memasukkan

Integer positif tunggal ndengan n > 2 format apa pun yang nyaman .

Keluaran

Array / daftar yang dihasilkan dari nresidu palindromik pertama , seperti diuraikan di atas. Sekali lagi, dalam format apa pun yang sesuai.

Aturan

  • Sebab n > 10, anggap daftar residu akan diratakan sebelum memeriksa apakah itu palindrom. Artinya, [1, 10, 11]palindromik, tetapi [1, 10, 1]tidak.
  • Program lengkap atau fungsi dapat diterima. Jika suatu fungsi, Anda dapat mengembalikan output daripada mencetaknya.
  • Jika memungkinkan, harap sertakan tautan ke lingkungan pengujian online agar orang lain dapat mencoba kode Anda!
  • Celah standar dilarang.
  • Ini adalah sehingga semua aturan golf biasa berlaku, dan kode terpendek (dalam byte) menang.

Contohnya

[input]
[output]

3
[1, 6, 7]

4
[1, 4, 5, 8]

5
[1, 50, 60, 61, 110]

6
[1, 30, 31, 60, 61, 90]

7
[1, 42, 43, 140, 182, 420, 421]

8
[1, 168, 169, 336, 337, 504, 505, 672]

9
[1, 2520, 2521, 5040, 5041, 7560, 7561, 10080, 10081]

10
[1, 280, 281, 560, 1611, 1890, 1891, 2170, 2171, 2241]

11
[1, 22682, 27720, 27721, 50402, 55440, 55441, 78122, 83160, 83161, 105842]

Apakah output seharusnya dipesan?
Arnauld

@Arnauld Tidak perlu, tidak, asalkan itu hanya mencakup nelemen pertama .
AdmBorkBork

2
arrgh ... tantangan Anda = aturan Anda, tetapi " [1, 10, 11]palindromik, tetapi [1, 10, 1]tidak" tampaknya secara matematis salah.
Greg Martin

1
@GregMartin Palindrom stringy, bukan palindrom mathy. ;-)
AdmBorkBork

1
Grr. Seluruh stringy bukannya palindrome matematika membuat ini seribu kali lebih sulit dalam bahasa tertentu. Baiklah.
MildlyMilquetoast

Jawaban:


9

Haskell, 57 byte

f n=take n[x|x<-[1..],(==)=<<reverse$show.mod x=<<[2..n]]

Contoh penggunaan: f 4-> [1,4,5,8]. Cobalah online!

Yang pertama =<<adalah dalam konteks fungsi dan diterjemahkan ke lambda \x -> reverse x == xdan yang kedua =<<dalam konteks daftar dan setara dengan concatMap, yaitu peta-dan-ratakan-satu-daftar-level.


5

05AB1E , 12 byte

µN2¹Ÿ%JÂQD½–

Cobalah online!

Penjelasan

µ              # until counter equals input do:
 N             # push current iterations number
     %         # modulus each in
  2¹Ÿ          # range [2 ... input]
      J        # joined to string
       ÂQ      # equals it's reverse
         D     # duplicate
          ½    # if true, increase counter
           –   # if true print iteration number

Apakah Anda mengirim jawaban 05AB1E dari ponsel Anda? Karena kamu melakukan lol cepat ini.
Magic Octopus Urn

@carusocomputing: Jarang sekali karena banyak karakter di cp-1252 menyebalkan untuk mengetik / menyalin-menempel pada telepon. Yang ini muncul tepat sebelum saya memeriksa komputer saya setelah makan malam, jadi saya punya waktu yang cukup baik :)
Emigna

4

Mathematica, 79 byte

NestList[#+1//.x_/;!PalindromeQ[ToString/@Mod[x,Range@n+1]<>""]:>x+1&,1,n=#-1]&

4

JavaScript (ES6), 104 byte

f=(n,x=(k=--n,2))=>k?([...Array(n)].map(_=>(r=x%++i+r,x%i),i=1,r='').join``==r?k--&&x+' ':'')+f(n,x+1):1

Demo

NB : Karena banyak panggilan rekursif, ini akan macet untuk n> 8 di Firefox atau n> 10 di Chrome.



3

MATL , 19 byte

Terima kasih kepada @AdmBorkBork karena menunjukkan kesalahan pada versi kode sebelumnya, sekarang diperbaiki

`@Gq:Q\VXztP=?@]NG<

Cobalah online!

Penjelasan

`        % Do...while
  @      %   Push iteration index, starting at 1
  Gq:Q   %   Push [2 3 ... n], where n is the input
  \      %   Modulo, element-wise
  V      %   Convert to string. Numbers are separated by spaces
  Xz     %   Remove spaces
  tP     %   Duplicate, flip
  =      %   Equal? (element-wise)
  ?      %   If all results were true
    @    %     Push current iteration index. It is one of the sought numbers
  ]      %   End
  N      %   Push number of elements in stack
  G      %   Push input n
  <      %   Less than? This is the loop condition
         % End (implicit). Display (implicit)

3

Scala, 90 86 82 byte

(n:Int)=>Stream.from(1)filter{i=>val d=(2 to n)map(i%)mkString;d.reverse==d}take(n)

Penjelasan

Stream.from(1)                              // From an infinite Stream starting from 1,
    filter ( i => {                         // keep only elements matching the next condition :
        val d=(2 to n)map(i%)mkString;      // Generate residues and convert to String,
        d.reverse==d                        // return true if palindrom, false otherwise
    })take(n)                               // Finally, take the n first elements matching the condition

Uji kasus

val f = (n:Int)=>...    // assign function
(3 to 11).foreach { i =>
    println(i + "\n" + f(i).mkString(", ") + "\n")
}

Hasil

3
1, 6, 7

4
1, 4, 5, 8

5
1, 50, 60, 61, 110

6
1, 30, 31, 60, 61, 90

7
1, 42, 43, 140, 182, 420, 421

8
1, 168, 169, 336, 337, 504, 505, 672

9
1, 2520, 2521, 5040, 5041, 7560, 7561, 10080, 10081

10
1, 280, 281, 560, 1611, 1890, 1891, 2170, 2171, 2241

11
1, 22682, 27720, 27721, 50402, 55440, 55441, 78122, 83160, 83161, 105842

Suntingan

# 1 (90 => 86)

  • fungsi anonim

# 2 (86 => 82)

  • hapus karakter titik yang tidak berguna setelah kurung atau kurung (mis.: (2 to n).map(%i)=>(2 to n)map(%i)

1
Selamat datang di PPCG!
Martin Ender

Terima kasih! Saya ingin tahu apakah aku bisa berubah def f(n:Int)=untuk (n:Int)=>, karena juga mendefinisikan fungsi (tapi tanpa nama). Menghemat 4 byte!
norbjd

Ya, fungsi yang tidak disebutkan namanya diizinkan , asalkan Anda tidak memerlukan nama untuk panggilan rekursif atau sesuatu seperti itu.
Martin Ender

Hebat, diedit :)
norbjd

2

Jelly , 12 byte

%ЀḊDFŒḂ
1ç#

Bagaimana?

1ç# - Main link: n
1   - initialise "i" at 1
  # - increment i and yield a list of the first n truthful results of:
 ç  -     last link (1) as a dyad

%ЀḊDFŒḂ - Link 1, test a value "i" for mod [2,n] being palindromic: i, n
 Ѐ      - for each, mapped over the right argument, i.e. for j = 1 to n:
%        -     i modulo j
   Ḋ     - dequeue, i.e. discard the modulo 1 result
    D    - convert to decimal list (vectorises)
     F   - flatten into one list
      ŒḂ - is palindromic?

Cobalah online!


1

CJam , 28 byte

0ri:N{{)_N),2>f%s_W%#}g_p}*;

Cobalah online!

Penjelasan

0          e# Push 0, the value we'll repeatedly increment to search for valid outputs.
ri:N       e# Read input, convert to integer, store in N.
{          e# Run this block N times...
  {        e#   Run this block until the condition is true, which will find the next
           e#   number with palindromic residues...
    )_     e#     Increment and duplicate.
    N),2>  e#     Push [2 3 ... N].
    f%     e#     Take the current value modulo each of these.
    s      e#     Flatten them into a single string.
    _W%    e#     Duplicate and reverse.
    #      e#     Try to find the reverse in the original. A common way to compute
           e#     "not equal" for strings of the same length.
  }g
  _p       e#   Print a copy of the result.
}*
;          e# Discard the final result to prevent printing it twice.

1

PHP, 93 Bytes

for(;$x<$a=$argn;$s="")for($i=1,++$n;$i++<$a;)if($i==$a&strrev($s.=$n%$i)==$s)echo$n._.!++$x;

Versi Online 2 Output Loop sebagai string

Diperluas

for(;$x<$a=$argn;$s="") 
for($i=1,++$n;$i++<$a;)
    if($i==$a&strrev($s.=$n%$i)==$s)echo$n._.!++$x; 

PHP 130 Bytes

for(;count($r)<$a=$argn;$s=[])for($i=1,++$n;$i++<$a;){$s[]=$n%$i;if(count($s)==$a-1&strrev($j=join($s))==$j)$r[]=$n; }print_r($r);

Versi Online 2 Loop

Diperluas

for(;count($r)<$a=$argn;$s=[])
for($i=1,++$n;$i++<$a;){
    $s[]=$n%$i;
    if(count($s)==$a-1&strrev($j=join($s))==$j)$r[]=$n; 
}
print_r($r);

PHP, 139 Bytes dengan 1 loop

for($i=$n=1;count($r)<($a=$argn)&$i++<$a;){$s[]=$n%$i;if(count($s)==$a-1){if(strrev($j=join($s))==$j)$r[]=$n;$n++;$s=[];$i=1;}}print_r($r);

Versi Online 1 Loop

Jalankan dengan

echo '<string>' | php -nR '<code>'

Diperluas

for($i=$n=1;count($r)<($a=$argn)&$i++<$a;){
    $s[]=$n%$i;
    if(count($s)==$a-1){
        if(strrev($j=join($s))==$j)$r[]=$n;
        $n++;
        $s=[];
        $i=1;
    }
}
print_r($r);

1

QBIC , 48 byte

:{A=G[2,a|A=A+!q%b$]~A=_fA||h=h+1?q]q=q+1~h=a|_X

Beats Mathematica! Contoh dijalankan:

Command line: 10
 1 
 280 
 281 
 560 
 1611 
 1890 
 1891 
 2170 
 2171 
 2241 

Penjelasan:

:{          Get 'a' from the command line, start an inf. loop
A=G         Clear out whatever's in A$
[2,a|       For each of the numbers we want to modulo
A=A+        Add to A$ 
     q%b       our current number MODULO te loop iterator
    !   $      cast to string
]           NEXT
~A=_fA|     If the string of remainders is a palindrome (_f ... | is Reverse())
|h=h+1      THEN h=h+1 (h starts at 0) - this counts how many hits we've had
 ?q            also, print the number with the palindromic remainder
]           END IF
q=q+1       Test the next number
~h=a|_X     If we've had 'a' hits, quit.
            The last IF and the infinite loop are closed implicitly.

1

Japt , 26 byte

L³o fR{C=Uò2@R%Xì ¥CwÃj1U

Cobalah online! Butuh beberapa detik pada semua input, jadi harap bersabar.

Ini akan jauh lebih singkat (dan lebih cepat) jika ada built-in untuk mendapatkan angka N pertama yang memenuhi beberapa kondisi:

R{C=Uò2@R%Xì ¥Cw}aU
Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.