Найбільші провідні показники


22

З огляду на ціле число n >= 2, виведіть найбільший показник у його основній факторизації. Це послідовність OEIS A051903 .

Приклад

Нехай n = 144. Його основна факторизація 2^4 * 3^2. Найбільший показник - це 4.

Випробування

2 -> 1
3 -> 1
4 -> 2
5 -> 1
6 -> 1
7 -> 1
8 -> 3
9 -> 2
10 -> 1
11 -> 1
12 -> 2
144 -> 4
200 -> 3
500 -> 3
1024 -> 10
3257832488 -> 3

Відповіді:







4

Python 2 , 78 байт

n=input()
e=m=0
f=2
while~-n:q=n%f<1;f+=1-q;e=q*-~e;m=max(m,e);n/=f**q
print m

Спробуйте в Інтернеті!

-5 завдяки ов .

Ця відповідь не робить простих перевірок. Натомість слід скористатися тим, що найвищий показник основного коефіцієнта буде більшим або рівним показнику будь-якого іншого фактора в будь-якій факторизації числа.



@ovs спасибі, пропустив це, поки я намагався швидко розмістити повідомлення
Ерік Аутгольфер


Нарешті, @ovs розслабився від if / else, спасибі
Ерік Аутгольфер

4

Japt -h , 9 7 байт

k ü mÊn

Спробуй це

k ü mÊn     :Implicit input of integer
k           :Prime factors
  ü         :Group by value
    m       :Map
     Ê      :  Length
      n     :Sort
            :Implicit output of last element

2
Я відчуваю, що це повинно бути набагато коротшим, можливо, я повинен додати вбудований для пар, що перебувають у
просторі

Навіщо використовувати "ü: Група за значенням" замість функції сортування? Так, можливо, тому що сортування повертає один масив, але нам потрібен один масив масивів ...
RosLuP

1
@RosLuP, Рівно; üстворює підмасиви рівних значень. Це робить також сортувати за вартістю першого , але це не має значення тут.
Кудлатий






2

Javascript 54 байти

* припускаючи нескінченний стек (як це роблять у коді-гольф виклики)

P=(n,i=2,k)=>i>n?k:n%i?k>(K=P(n,i+1))?k:K:P(n/i,i,-~k)

console.log(P(2 )== 1)
console.log(P(3 )== 1)
console.log(P(4 )== 2)
console.log(P(5 )== 1)
console.log(P(6 )== 1)
console.log(P(7 )== 1)
console.log(P(8 )== 3)
console.log(P(9 )== 2)
console.log(P(10 )== 1)
console.log(P(11 )== 1)
console.log(P(12 )== 2)
console.log(P(144 )== 4)
console.log(P(200 )== 3)
console.log(P(500 )== 3)
console.log(P(1024 )== 10)
//console.log(P(3257832488 )== 3)



2

Октава , 25 байт

@(n)[~,m]=mode(factor(n))

Спробуйте в Інтернеті!

Пояснення

factorстворює масив (можливо повторних) простих експонентів. Другий висновок modeдає кількість разів, коли з'являється режим (тобто найбільш повторений запис).




1

Gaia, 4 bytes

ḋ)⌠)

Try it online!

  • - Computes the prime factorization as [prime, exponent] pairs.

    • - Map and collect the result with the maximal value.

    • ) - Last element (exponent).

    • ) - Last element (maximal exponent)

Gaia, 4 bytes

ḋ)¦⌉

Try it online!

  • - Computes the prime factorization as [prime, exponent] pairs.

    • - Map with the last element (exponent).

    • - Gets the maximum element.



1

Octave: 30 bytes

@(x)max(histc(a=factor(x),a));
  1. a=factor(x) returns a vector containing the prime factors of x. This is a vector sorted in ascending order where the multiplication of all numbers in factor(x) yields x itself such that each number in the vector is prime.
  2. histc(...,a) calculates a histogram on the prime factor vector where the bins are the prime factors. The histogram counts up how many times we have seen each prime number thus yielding the exponent of each prime number. We can cheat here a bit because even though factor(x) will return duplicate numbers or bins, only one of the bins will capture the total amount of times we see a prime number.
  3. max(...) thus returns the largest exponent.

Try it online!


1

Alice, 17 bytes

/o
\i@/w].D:.t$Kq

Try it online!

Explanation

/o
\i@/...

This is just a framework for simple-ish arithmetic programs with decimal I/O. The ... is the actual program, which already has the input on the stack and leaves the output on top of the stack.

Alice actually has built-ins to get the prime factorisation of an integer (even with prime-exponent pairs), but the shortest I've come up with using those is 10 bytes longer than this.

Instead the idea is that we repeatedly divide one copy of each distinct prime factor out of the input, until we reach 1. The number of steps this takes is equal to the largest prime exponent. We'll be abusing the tape head as the counter variable.

w      Remember the current IP position. Effectively starts a loop.
  ]      Move the tape head to the right, which increments our counter.
  .D     Duplicate the current value, and deduplicate its prime factors.
         That means, we'll get a number which is the product of the value's
         unique prime factors. For example 144 = 2^4 * 3^2 would become
         6 = 2 * 3.
  :      Divide the value by its deduplicated version, which decrements the
         exponents of its prime factors.
  .t     Duplicate the result and decrement it. This value becomes 0 once we
         reach a result of 1, which is when we want to terminate the loop.
$K     Jump back to the beginning of the loop if the previous value wasn't 0.
q      Retrieve the tape head's position, i.e. the number of steps we've taken
       through the above loop.

1

Julia, 60 52 40 bytes

f(x)=maximum(collect(values(factor(x))))

-12 +correction thanks to Steadybox


1
I think you need to add a call to print(). Also, I couldn't get the code to run on TIO as is, I assume it works on some other version of the language not available there? This runs fine on TIO: print(maximum(collect(values(factor(parse(BigInt,readline()))))))
Steadybox

This works on the interpreter (on my computer, at least). It also causes a warning because initializing a BigInt like that has been deprecated. Nonetheless, if you copy and paste the code as-is into a Julia interpreter, it should work. (if a print is required because it has to explicitly be printed, ill put that in)
EricShermanCS

1
The print() is needed because the answer needs to be a full program (that displays the output) or a function (that returns the output). Otherwise your solution is fine. It seems that you can save some bytes (and avoid the print) this way: f(x)=maximum(collect(values(factor(x))))
Steadybox

1
You're welcome! Here's a meta post on what is the allowed format for a solution.
Steadybox

0

Actually, 4 bytes

w♂NM

Try it online!

w♂NM  - Full program.

w     - Pushes the prime factorization as [prime, exponent] pairs.
 ♂N   - Get the last element of each (the exponents).
   M  - Maximum.

I used this exact solution for writing the test cases :)
Mego

@Mego Do you think it can get shorter (I don't want you to spoil if you have a shorter one, just asking)? :)
Mr. Xcoder

No, I believe this is optimal for Actually.
Mego

0

Python 2, 64 bytes

-4 bytes thanks to H.PWiz.

lambda n:max(a*(n%k**a<1)for a in range(n)for k in range(2,-~n))

Try it online!

Port of H.PWiz's Haskell answer. I'm only sharing this because I'm proud that I was able to understand this piece of Haskell code and translate it. :P


Does range(1,n) not work?
H.PWiz

range(1, n) produces all integers in [1, n).
totallyhuman

1
Ah, well you don't actually need to go all the way up to n for a
H.PWiz

Oh, okay, I don't completely understand the math behind it. :P Thanks!
totallyhuman


0

Axiom, 61 bytes

f n==(a:=factors n;reduce(max,[a.i.exponent for i in 1..#a]))

This is the first time i find it is possible define the function without the use of () parenthesis. Instead of "f(n)==" "f n==" one character less...


0

Racket, 83 79 bytes

(λ(n)(cadr(argmax cadr((let()(local-require math/number-theory)factorize)n))))

Try it online!

(I'm not sure if there's a consensus on what constitutes a complete Racket solution, so I'm going with the Mathematica convention that a pure function counts.)

How it works

factorize gives the factorization as a list of pairs: (factorize 108) gives '((2 2) (3 3)). The second element of a pair is given by cadr, a shorthand for the composition of car (head of a list) with cdr (tail of a list).

I feel silly doing (cadr (argmax cadr list)) to find the maximum of the second elements, but max doesn't work on lists: (max (map cadr list)) doesn't do what we want. I'm not an expert in Racket, so maybe there's a standard better way to do this.

Racket, 93 bytes

(λ(n)(define(p d m)(if(=(gcd m d)d)(+(p d(/ m d))1)0))(p(argmax(λ(d)(p d n))(range 2 n))n))

Try it online!

How it works

An alternative version that doesn't import factorize and instead does everything from scratch, more or less. The function (p m d) finds the highest power of d that divides m and then we just find highest value of (p n d) for d between 2 and n. (We don't need to restrict this to primes, since there will not be a composite power that works better than prime powers.)


I guess the standard max solution is (apply max (map cadr list) but (cadr (argmax cadr list)) is unfortunately shorter.
Misha Lavrov


0

APL(NARS), 15 chars, 30 bytes

{⌈/+/¨v∘=¨v←π⍵}

test:

  f←{⌈/+/¨v∘=¨v←π⍵}
  f¨2..12
1 1 2 1 1 1 3 2 1 1 2 
  f¨144 200 500 1024 3257832488
4 3 3 10 3 

comment:

{⌈/+/¨v∘=¨v←π⍵}
          v←π⍵    π12 return 2 2 3; assign to v the array of prime divisors of argument ⍵
      v∘=¨        for each element of v, build one binary array, show with 1 where are in v array, else puts 0 
                  return one big array I call B, where each element is the binary array above
   +/¨            sum each binary element array of  B
 ⌈/               get the max of all element of B (that should be the max exponet)
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.