Najwyższy lub najwyższy czynnik

14

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 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 Njest 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


źródło
2
I highly recommend using the Sandbox for future questions, to provide feedback on questions before posting them
Jo King
@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
4
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
5
Define highest factor. Should I return the number itself? The highest divisible prime? The highest factor that isn't itself?
Nissa
2
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

Odpowiedzi:

9

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]
Jonathan Allan
źródło
8

Jelly, 9 8 bytes

Saved 1 byte thanks to @Dennis

:ÆfṂ€$~~

Try it online! or run all test cases

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)
Arnauld
źródło
3
You didn't use JavaScript this time ? nice answer btw
3
I really like the ~~. :ÆfṂ€$~~ saves a byte by eliminating the helper link.
Dennis
@Dennis Ah! $ is what I was looking for. :) Thanks!
Arnauld
7

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
źródło
2
62 bytes
Giuseppe
nice — didn't think to initialise with !
JDL
6

05AB1E, 11 9 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]
Kevin Cruijssen
źródło
1
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
@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
1
Or even better: Ñε¨àDd<+
Emigna
Much better than my 12-byter.
Magic Octopus Urn
5

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:

Galen Ivanov
źródło
4

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
Shaggy
źródło
Save a byte with -m
Oliver
3

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!

ovs
źródło
3

Java 8, 105 103 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)
Kevin Cruijssen
źródło
3

Haskell, 52 49 bytes

map(\x->last$[d|d<-[1..x-1],mod x d<1]++[-1|x<2])

Try it online!

map                     -- for each element in the input array
  \x->                  -- apply the lambda function
    last                -- pick the last element of the following list
     [d|d<-[1..x-1]     --  all d from 1 to x-1 
           ,mod x d<1]  --    where d divides x 
     ++[-1|x<2]         --  followed by -1 if x<2
nimi
źródło
3

Husk, 8 bytes

m(|_1→hḊ

Try it online!

Explanation

m(|_1→hḊ  Implicit Input         [1,2,3,4,10]
m(        Map each element
       Ḋ    List of divisors     [[1],[1,2],[1,3],[1,2,4],[1,2,5,10]]
     →h     Penultimate element  [0,1,1,2,5]
  |_1       If falsy then -1     [-1,1,1,2,5]
Fyr
źródło
3

Attache, 23 bytes

@{Max&-1!Divisors@_@-2}

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 is nil, and Max[-1, nil] is -1. @ simply vectorizes this function, making it apply to each atom.

Conor O'Brien
źródło
2

R + numbers, 88 79 bytes

Thanks to the comments for some advice mainly about how to make submissions.

function(y)sapply(y,function(x)"if"(x<2,-1,prod(numbers::primeFactors(x)[-1])))

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!

ngm
źródło
1
saves bytes to omit the library call and use numbers::primeFactors directly.
JDL
1
here's a TIO link to see what JDL is suggesting, as well as swapping this to an anonymous function.
Giuseppe
2

Brachylog, 10 bytes

{fkt|∧_1}ˢ

Try it online!

The following explanation is mostly phrased imperatively for the sake of brevity, and does not accurately reflect Brachylog's declarative nature.

{          Start of inline predicate.
           Implicit input to the predicate.
 f         Create a list of all of the input's factors (including itself).
  k        Remove the last item of this list so that it no longer contains the original number.
   t       Take the last item of the list with the last item removed.
           Implicitly unify the output with the aforementioned last item.
    |      If that failed, because one of the lists was empty...
     ∧     discarding the input, (there's probably some obvious reason ∨ won't work here but I don't know what it is)
      _1   unify the output with -1 instead.
        }  End of the inline predicate.
         ˢ For every item of the input, unify it with the predicate's input and get a list of the corresponding outputs.

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.

Unrelated String
źródło
2
"there's probably some obvious reason ∨ won't work here but I don't know what it is" -> You can use .∨ 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!
Fatalize
Ah, of course! Thanks.
Unrelated String
You can ask these kinds of questions on Brachylog in the Brachylog chat room
Fatalize
1

Stax, 14 13 bytes

ü±p╞Ö*«òτ♀╣â▀

Run and debug it

Explanation (unpacked):

m|fc%c{vsH1?}U? Full program, implicit input-parsing
m               Map
 |fc%c            Get factorisation and length of it (0 and 1 yield [])
      {     } ?   If length != 0:
       v            Decrement
           ?        If still != 0:
        sH            Last element of factorisation
           ?        Else:
          1           Push 1
              ?   Else:
             U      Push -1

Pseudocode inside map:

f = factorisation(i)
l = length(f)
if l:
    if --l:
        return f[-1]
    else:
        return 1
else:
    return -1
wastl
źródło
1

Pyth, 12 bytes

me+_1f!%dTSt

Try it here

Explanation

me+_1f!%dTSt
m            Q    For each number d in the (implicit) input...
          Std     ... get the range [1, ..., d - 1]...
     f!%dT        ... take the ones that are factors of d...
  +_1             ... prepend -1...
 e                ... and take the last.

źródło
1

J, 14 bytes

1(%0{q:,-)@>.]

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

(%0{q:) ::_1"0

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.

FrownyFrog
źródło
Very nice solutions!
Galen Ivanov
1

Japt, 14 11 8 bytes

®/k v)ªÉ
®        // For each input number,
 /k v    // return the number divided by it's first prime factor,
     )ªÉ // or -1 if such a number doesn't exist (the previous result is NaN).

Try it online!

Shaved off those three pesky bytes thanks to Shaggy.

Nit
źródło
You don't need to filter the primes - k returns the prime factors of N - so this becomes 8 bytes: ®/k v)ªÉ
Shaggy
@Shaggy Thanks, didn't know it only returns the prime factors since the method docs don't say that.
Nit
1
Oh, yeah, forgot that. Been meaning to submit a PR for that for a while; will do so shortly.
Shaggy
1

JavaScript (Node.js), 6155 bytes

-6 bytes thanks to @shaggy

_=>_.map(_=>eval('for(v=_/(d=_>>1);v!=~~v;v=_/--d);d'))

Try it online!


Explanation :

_ =>                                     // input i.e : the original array
    _.map(                               // map over all elements of the array
        eval('                           // eval a string
            for(v=_/(d=_>>1);            // set v = _ / _ >> 1 and set that to d
                v!=~~v;                  // and keep going until v !== floor(v)
                        v=_/d--);        // to _ / d again (d was changed)
                    d'                   // return d
            ))                           // end eval and map and function

This is still for old code haven't updated this.

ES5 friendly as well:

 const primeOrNot = function(input) { // the function with argument input
      return input.map(function(value) { // returns the array after mapping over them
           d = Math.floor(value * 0.5); // multiply each element by 0.5 and floor it 
           for(let v = value / d; v != Math.floor(v);) { // for loop goes until v!=~~v
                d --; // subtract one from d
                v = value / d; // set v again to value / d
           }
           return d; // return d
      })
 };
Muhammad Salman
źródło
55 bytes
Shaggy
@Shaggy : thanks
Muhammad Salman
1

Bash + GNU utilities, 49

  • 9 bytes saved thanks to @Cowsquack
factor|sed '/:$/c-1
/: \w+$/c1
s%: %/%
y/ /#/'|bc

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 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!

Digital Trauma
źródło
1
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/…
user41805
@Cowsquack very good - thanks!
Digital Trauma
1

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!

Jonathan Frech
źródło
1

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

MildlyMilquetoast
źródło
0

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.

Neil
źródło
0

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
DLosc
źródło