Wyzwanie:
Biorąc pod uwagę tablicę nieujemnych liczb całkowitych w zakresie0 to Infinity
, sprawdź, czy wszystkie są liczbami pierwszymi, czy nie. (Jeśli chcesz, możesz również wprowadzić dane jako ciąg znaków)
Wejście:
Dane wejściowe: tablica liczb
Dane wyjściowe: tablica z każdym elementem zastąpionym przez jeden z tych:
-1 -----> If 0, 1
1 -----> If it is a prime number greater than 1
the highest factor -----> If that number is not prime
Zwraca -1 (0, 1), 1 (dla liczb pierwszych> = 2) lub najwyższy współczynnik podanej liczby (dla liczb pierwszych)
Przykłady:
[1, 2, 3, 4, 10, 11, 13] ---> [-1, 1, 1, 2, 5, 1, 1]
[100, 200, 231321, 12312, 0, 111381209, 123123] ---> [50, 100, 77107, 6156, -1, 1, 41041]
Uwaga:
Dane wejściowe zawsze będą prawidłowe, tzn. Będą się składać tylko z liczb, a liczby dziesiętne nie będą testowane. Tablica może być pusta, jeśli tak, zwróć pustą tablicę.
Ograniczenie:
To jest golf golfowy, więc wygrywa najkrótszy kod w bajtach dla każdego języka.
Tablica wyników:
Oto fragment kodu, który pozwala wygenerować zarówno zwykłą tabelę wyników, jak i przegląd zwycięzców według języka.
Aby upewnić się, że twoja odpowiedź się pojawi, zacznij od nagłówka, korzystając z następującego szablonu Markdown:
# Language Name, N bytes
gdzie N
jest rozmiar twojego zgłoszenia. Jeśli poprawić swój wynik, to może zachować stare porachunki w nagłówku, uderzając je przez. Na przykład:
# Ruby, <s>104</s> <s>101</s> 96 bytes
Jeśli chcesz umieścić w nagłówku wiele liczb (np. Ponieważ twój wynik to suma dwóch plików lub chcesz osobno wymienić kary za flagi tłumacza), upewnij się, że rzeczywisty wynik jest ostatnią liczbą w nagłówku:
# Perl, 43 + 2 (-p flag) = 45 bytes
Możesz także ustawić nazwę języka jako link, który pojawi się we fragmencie tabeli wyników:
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
var QUESTION_ID=163882,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
Odpowiedzi:
Jelly,
76 bytesA monadic link accepting a list of non-negative integers and returing a list of integers greater than or equal to -1.
Try it online!
How?
Note that:
ÆḌ
, yields a list of proper divisors in ascending orderṪ
, to an empty list yields zeroźródło
Jelly,
98 bytesSaved 1 byte thanks to @Dennis
Try it online! or run all test cases
Commented
We take advantage of the fact that both
nan
andinf
become0
in Jelly when a bitwise NOT is applied to them.źródło
~~
.:ÆfṂ€$~~
saves a byte by eliminating the helper link.$
is what I was looking for. :) Thanks!R,
6862 bytesA solution using only base R, no libraries! Thanks to Giuseppe for golfing away 6 bytes.
Uses
scan
to read in a space separated list of numbers,%%
to identify which are factors.v
then contains a vector of all factors in ascending order (including 1 and n). This has the nice property that when werev
ersev
, the number we want will be in the second place, avoiding an expensive call tolength
ortail
(ifn
was prime,v
containsn 1
, else it containsn (factors in descending order) 1
).Example output (TIO link here):
If you think a list is not an acceptable return type, then swap out
Map
forsapply
and add 3 bytes.źródło
!
05AB1E,
1198 bytes-3 bytes thanks to @Emigna, changing
©d1-®+
toDd<+
and۬ۈ
toε¨à
.Only my second 05AB1E answer,
so can definitely be golfed.Try it online.
Explanation:
źródło
Dd<+
should work instead of©d1-®+
. You also don't need theï
as they are still ints. You could have it in the footer for nicer looking output though.1-
instead of<
was pretty stupid.. Thanks for theD
instead of©...®
! And I've indeed put theï
in the footer now.Ñε¨àDd<+
J, 21 bytes
Try it online!
Explanation:
(>&1)"0
is each number greater than 1?@.
if not, return_1:
(%{.@q:)
if its 2 or greater, divide%
the number by the first{.
of the prime factorsq:
źródło
Japt, 6 bytes
After golfing, ended up being almost identical to, and just as short as, Jonathan's solution.
Try it
Explanation
źródło
-m
Python 3, 62 bytes
Try it online!
For
0
and1
range(1,n)
is empty, therefore the code evaluates tomax([]+[-1]) = -1
. For prime numbers, the only divisor in the [1, n) is1
, which is the desired output.Coconut, 50 bytes
Try it online!
źródło
Java 8,
10510387 bytesModifies the input-array instead of returning a new one to save bytes.
Try it online.
Explanation:
źródło
Haskell,
5249 bytesTry it online!
źródło
Husk, 8 bytes
Try it online!
Explanation
źródło
Attache, 23 bytes
Try it online!
29 bytes, pointfree:
@(Max&-1@Last@ProperDivisors)
24 bytes, also pointfree:
@(Max&-1@`@&-2@Divisors)
This simply gets the second-to-last divisor of
n
then takes the max of it and-1
. The second-to-last element in an array with less than two elements isnil
, andMax[-1, nil]
is-1
.@
simply vectorizes this function, making it apply to each atom.źródło
Wolfram Language (Mathematica), 33 bytes
Try it online!
źródło
R +
numbers
,8879 bytesThanks to the comments for some advice mainly about how to make submissions.
Uses the product of all prime factors except the smallest one, and the fact that the product of elements of an empty vector is defined to be
1
.Try it online!
źródło
library
call and usenumbers::primeFactors
directly.Brachylog, 10 bytes
Try it online!
The following explanation is mostly phrased imperatively for the sake of brevity, and does not accurately reflect Brachylog's declarative nature.
I decided I'd learn Brachylog so I could have some fun with code golf while hoping to learn some of the behavior of actual Prolog through osmosis, and I'm really enjoying it so far, even if I'm not entirely sure how the execution control characters work.
źródło
.∨
instead of|∧
(I'm guessing you forgot the.
), but it's the same byte count. Welcome to PPCG (and Brachylog more importantly :p) by the way!Stax,
1413 bytesRun and debug it
Explanation (unpacked):
Pseudocode inside map:
źródło
Pyth, 12 bytes
Try it here
Explanation
źródło
J, 14 bytes
Try it online!
For every number n take the maximum of (n,1) instead.
Append the negated number to the list of its prime factors (empty list for 1), and divide the number by the first item in the list.
Also 14 bytes
Try it online!
Divide every number by the first of its prime factors. 0 raises a domain error with
q:
, and we look for the 0th item in an empty list for 1 — that’s an error as well. For any number that errors, return −1.źródło
Japt,
14118 bytesTry it online!
Shaved off those three pesky bytes thanks to Shaggy.
źródło
k
returns the prime factors ofN
- so this becomes 8 bytes:®/k v)ªÉ
JavaScript (Node.js),
6155 bytes-6 bytes thanks to @shaggy
Try it online!
Explanation :
This is still for old code haven't updated this.
ES5 friendly as well:
źródło
Bash + GNU utilities, 49
Explanation
factor
reads input numbers from STDIN, one per line and outputs in the format<input number>: <space-separated list of prime factors (ascending)>
sed
processes this as follows:/:$/c-1
The input numbers 0 and 1 have no prime factors and are replaced with-1
/: \w+$/c1
Numbers with one prime factor (themselves) are prime. Replace these with1
s%: %/%
Replace:
with/
. This builds an arithmetic expression to divide the (non-prime) input number by its smallest prime factor to give the largest factory/ /#/
Remove the list of other (unneeded) factors (by commenting out)bc
Arithmetically evaluate and displayTry it online!
źródło
-r
, and for the first twos
's you can use/regex/cvalue
to golf a byte, simplifying this regex further can save more, and you can save a byte in the last two regex's by only replacing the:
with the/
, and then commenting out the unwanted part, like so, tio.run/##JYlBCoMwFET3c4qABhdSfuZ/…Python 2,
6159 bytesTry it online!
Improvements
źródło
JavaScript (Node.js), 37 bytes
Try it online!
Recursive, stack overflow for large input
JavaScript (Node.js), 41 bytes
Try it online!
źródło
Pari/GP, 37 bytes
Try it online!
źródło
Racket, 105 bytes
Try it online!
źródło
Befunge-98 (FBBI), 39 bytes
Try it online!
Ends with the
&
when there are no more numbers. This causes the program to stall for 60 seconds until TIO ends the program. This is unavoidable for Befunge-98, at least on TIO because both interpreters do this. After hitting play, you can stop the program after a bit in order to see what would be output if you did wait the minute.Essentially, for every new number, if it is 0, it turns it into a 1. Then it puts a -1 onto the stack followed by a number that starts from 1 and counts up until it reaches the input number, in which case it prints out the second number on the stack (-1 for an input of 0 or 1, and the highest factor for others). Every time through the loop, we add the value of the iterator to the stack behind it if (
input % iterator == 0
). This means that when we get to the input, we just have to throw away the iterator and print. Then, we clear the stack withn
and return to the read input function.I may expand of the explanation later, we'll see...
źródło
Retina 0.8.2, 33 bytes
Try it online! Link includes those test cases that aren't too slow. Explanation:
Loop over each input number.
Special-case 0 and 1.
Convert to unary (doesn't affect -1).
Replace each number with its largest proper factor in decimal.
źródło
tinylisp, 75 bytes
Try it online! (Contains 4 extra bytes to give the anonymous function a name so we can call it in the footer.)
Ungolfed/explanation
Observe that returning 1 for primen and the largest factor less than n for composite n can be combined into returning n/p where p is the smallest prime factor of n .
źródło