# Challenge:

Given an array of non-negative whole numbers numbers in the range of 0 to Infinity, Check whether all of them are primes or not. (You can take input as a string too if you want)

# Input:

Input: An array of numbers

Output: The array with every element replaced by one of these:

-1                 -----> If 0, 1
1                  -----> If it is a prime number greater than 1
the highest factor -----> If that number is not prime


Return either -1 (0, 1), 1 (for primes >= 2) or the highest factor of given number (for non-primes)

# Examples:

[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]


# Note:

Input will always be valid, i.e it will consist only of numbers and decimals are not tested for. The array can be empty, if so, return the empty array.

# Restriction:

This is so shortest code in bytes for each language wins.

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

# Language Name, N bytes


where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

# Ruby, <s>104</s> <s>101</s> 96 bytes


If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

# Perl, 43 + 2 (-p flag) = 45 bytes


You can also make the language name a link which will then show up in the leaderboard snippet:

# [><>](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>

• I highly recommend using the Sandbox for future questions, to provide feedback on questions before posting them – Jo King May 1 '18 at 9:47
• @Joking : for infinity you must output all numbers upto infinity. This is just for you and you also have to make sure it doesn't time out or anything. JK : time out error is the most likely thing you will get for infinity – user79855 May 1 '18 at 9:49
• just wanted to note that in "If it is a prime number greater than 1" greater than 1 really is not necessary because prime numbers are always greater than 1 – Ivo Beckers May 1 '18 at 10:59
• Define highest factor. Should I return the number itself? The highest divisible prime? The highest factor that isn't itself? – Nissa May 1 '18 at 15:39
• I take it our programs are only required to work for integers up to our chosen language's max integer size (for those that don't have support for arbitrarily large integers) – JDL May 1 '18 at 16:18

# Jelly,  7 6 bytes

ÆḌṪ€o-


A 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:

• All primes have a single proper divisor (one)
• All composites have multiple proper divisors (one plus the others)
• No number has itself as a proper divisor
• Jelly's get-proper-divisors atom, ÆḌ, yields a list of proper divisors in ascending order
• Zero and one have no proper divisors (they are neither prime, nor composite)
• Applying Jelly's tail atom, Ṫ, to an empty list yields zero
• No number has a proper divisor of zero (let alone being the maximal one)
• All non-zero numbers are truthy in Jelly, while zero is falsey

ÆḌṪ€o- | Link: list of integers   e.g. [ 0, 1,  2,  5,     10,    5183]
ÆḌ     | proper divisors (vectorises)  [[],[],[1],[1],[1,2,5],[1,71,73]]
Ṫ€   | tail €ach                     [ 0, 0,  1,  1,      5,      73]
- | literal minus one
o  | logical OR (vectorises)       [-1,-1,  1,  1,      5,      73]


# Jelly, 9 8 bytes

Saved 1 byte thanks to @Dennis

:ÆfṂ€$~~  ### Commented We take advantage of the fact that both nan and inf become 0 in Jelly when a bitwise NOT is applied to them. :ÆfṂ€$~~ - main link, taking the input list
ÆfṂ€$- treat these two links as a monad: Æf - get the lists of prime factors (0 --> 0; 1 --> empty list; prime --> itself) € - for each list, Ṃ - isolate the minimum prime factor (turns empty lists into 0) : - divide each entry by its minimum prime factor (0/0 --> nan; 1/0 --> inf) ~~ - bitwise NOT x2 (nan or inf --> 0 --> -1; other entries are unchanged)  • You didn't use JavaScript this time ? nice answer btw – user79855 May 1 '18 at 8:44 • I really like the ~~. :ÆfṂ€$~~ saves a byte by eliminating the helper link. – Dennis May 1 '18 at 13:51
• @Dennis Ah! $ is what I was looking for. :) Thanks! – Arnauld May 1 '18 at 14:01 # R, 68 62 bytes Map(function(n,v=rev(which(!n%%1:n)))"if"(n<2,-1,v[2]),scan())  A 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 we reverse v, the number we want will be in the second place, avoiding an expensive call to length or tail(if n was prime, v contains n 1, else it contains n (factors in descending order) 1). Example output (TIO link here): > Map(function(n,v=rev(which(!n%%1:n)))"if"(n<2,-1,v[2]),scan()) 1: 0 1 2 3 4 5 6 7 8 9 11: Read 10 items [[1]] [1] -1 [[2]] [1] -1 [[3]] [1] 1 [[4]] [1] 1 [[5]] [1] 2 [[6]] [1] 1 [[7]] [1] 3 [[8]] [1] 1 [[9]] [1] 4 [[10]] [1] 3  If you think a list is not an acceptable return type, then swap out Map for sapply and add 3 bytes. • 62 bytes – Giuseppe May 1 '18 at 16:28 • nice — didn't think to initialise with ! – JDL May 1 '18 at 16:42 # 05AB1E, 119 8 bytes Ñε¨àDd<+  -3 bytes thanks to @Emigna, changing ©d1-®+ to Dd<+ and €¨€à to ε¨à. Only my second 05AB1E answer, so can definitely be golfed. Try it online. Explanation: Ñ # Divisors of each item in the input-list (including itself) # [1,2,10,3] → [[1],[1,2],[1,2,5,10],[1,2,3]] ε # For each: ¨ # Remove last item (so it's now excluding itself) # [[1],[1,2],[1,2,5,10],[1,2,3]] → [[],[1],[1,2,5],[1,2]] à # And get the max # [[],[1],[1,2,5],[1,2]] → ['',1,5,2] D # Duplicate the list d # Is it a number (1 if it's a number, 0 otherwise) # ['',1,5,2] → [0,1,1,1] < # Subtract 1 # [0,1,1,1] → [-1,0,0,0] + # Add both lists together # ['',1,5,2] and [-1,0,0,0] → ['-1',1,5,2]  • 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. – Emigna May 1 '18 at 14:16 • @Emigna Ah, 1- instead of < was pretty stupid.. Thanks for the D instead of ©...®! And I've indeed put the ï in the footer now. – Kevin Cruijssen May 1 '18 at 14:22 • Or even better: Ñε¨àDd<+ – Emigna May 1 '18 at 14:32 • Much better than my 12-byter. – Magic Octopus Urn May 1 '18 at 16:07 # J, 21 bytes _1:(%{.@q:)@.(>&1)"0  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 factors q: # Japt, 6 bytes After golfing, ended up being almost identical to, and just as short as, Jonathan's solution. ®â¬ÌªJ  Try it ## Explanation ® :Map â¬ : Proper divisors Ì : Get last element (returns null if the array is empty) ª : Logical OR J : -1  • Save a byte with -m – Oliver Feb 23 at 0:14 # Python 3, 62 bytes lambda l:[max([k for k in range(1,n)if n%k<1]+[-1])for n in l]  Try it online! For 0 and 1 range(1,n) is empty, therefore the code evaluates to max([]+[-1]) = -1. For prime numbers, the only divisor in the [1, n) is 1, which is the desired output. # Coconut, 50 bytes map$(n->max([k for k in range(1,n)if n%k<1]+[-1]))


Try it online!

# Java 8, 105103 87 bytes

a->{for(int i=a.length,n,x;i-->0;a[i]=n<2?-1:n/x)for(n=a[i],x=1;++x<n;)if(n%x<1)break;}


Modifies the input-array instead of returning a new one to save bytes.

Try it online.

Explanation:

a->{                  // Method with integer-array parameter and no return-type
for(int i=a.length,n,x;i-->0;
//  Loop backward over the array
a[i]=           //    After every iteration: change the current item to:
n<2?       //     If the current item is 0 or 1:
-1        //      Change it to -1
:          //     Else:
n/x)      //      Change it to n divided by x
for(n=a[i],      //   Set n to the current item
x=1;++x<n;)  //   Inner loop x in range [2,n)
if(n%x<1)      //    If n is divisible by x:
break;}      //     Stop the inner loop (x is now the smallest prime-factor)
//   (if the loop finishes without hitting the break,
//    it means n is a prime, and x and n will be the same)


• /: \w+$/c1 Numbers with one prime factor (themselves) are prime. Replace these with 1 • s%: %/% Replace : with /. This builds an arithmetic expression to divide the (non-prime) input number by its smallest prime factor to give the largest factor • y/ /#/ Remove the list of other (unneeded) factors (by commenting out) • bc Arithmetically evaluate and display Try it online! • You might be able to drop the -r, and for the first two s'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/… – Kritixi Lithos May 1 '18 at 17:51 • @Cowsquack very good - thanks! – Digital Trauma May 1 '18 at 18:01 # Python 2, 61 59 bytes lambda x:[max(k for k in[-1]+range(1,n)if n%k<1)for n in x]  Try it online! Improvements # JavaScript (Node.js), 37 bytes x=>x.map(a=>(f=t=>a%--t<1?t:f(t))(a))  Try it online! Recursive, stack overflow for large input # JavaScript (Node.js), 41 bytes x=>x.map(a=>eval('for(t=a;a%--t!=0;);t'))  Try it online! # Pari/GP, 37 bytes a->[if(x<2,-1,x/divisors(x)[2])|x<-a]  Try it online! # Racket, 105 bytes (λ(L)(map(λ(n)(if(< n 2)-1(p n(- n 1))))L))(define(p n d)(if(= d 1)1(if(=(modulo n d)0)d(p n(- d 1)))))  Try it online! # Befunge-98 (FBBI), 39 bytes j&:!+f0p1-1:::' -:!j;3k$.nbj;-\%!!j:1+a


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 with n and return to the read input function.

I may expand of the explanation later, we'll see...

# Retina 0.8.2, 33 bytes

%(^0|^1$-1 \d+$*
^(1+)\1+.1


Try it online! Link includes those test cases that aren't too slow. Explanation:

%(


Loop over each input number.

^0|^1$-1  Special-case 0 and 1. \d+$*


Convert to unary (doesn't affect -1).

^(1+)\1+.1


Replace each number with its largest proper factor in decimal.

# tinylisp, 75 bytes

(load library
(q((L)(map(q((N)(i(l N 2)(- 1)(/ N(min(prime-factors N))))))L


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 prime $$\n\$$ 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\$$.

(load library)               Library gives us map, -, /, min, and prime-factors functions

(lambda (L)                  Anonymous function, takes a list of numbers L
(map                         Map
(lambda (N)                  Anonymous function, takes a number N
(if (less? N 2)              If N < 2
(- 1)                        -1; else
(/ N                         N divided by
(min                        the minimum
(prime-factors N)))))      of the prime factors of N
L)))                        ... to L