Skip to main content
5 of 6
added 9 characters in body
JDL
  • 1.8k
  • 13
  • 18

#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.

JDL
  • 1.8k
  • 13
  • 18