0
$\begingroup$

I would like to find the powers of a prime in the unique prime factorization of an $n$. I want a function $f[n,p]$ such that $n,p$ are given and I need to know what the power of $p$ is. For instance

n=60;
f[n,2]=2;
f[n,3]=1;
f[n,5]=1;
f[n,7]=0;
$\endgroup$
  • 2
    $\begingroup$ maybe f[n_, p_] := Cases[FactorInteger[n], {p, e_} :> e]? $\endgroup$ – kglr Oct 28 '16 at 21:06
  • 2
    $\begingroup$ If you want efficiency when dealing with large inputs, just use division. getPower[n_, p_ /; Abs[p] != 1] := Module[{i = 0, q = n}, While[Divisible[q, p], i++; q /= p]; i] $\endgroup$ – Daniel Lichtblau Oct 28 '16 at 21:24
4
$\begingroup$

If you really mean, as you say, that $n$ and $p$ are given, so you could simply use IntegerExponent[n,p].

$\endgroup$
  • $\begingroup$ I can't believe I missed that. Again (yes, it's happened before). $\endgroup$ – Daniel Lichtblau Oct 29 '16 at 18:59
1
$\begingroup$
f[n_, p_] := 
 Block[{s}, s = Select[FactorInteger[n], MemberQ[#, p] &]; 
  If[s == {}, 0, s[[1, 2]]]]

or

f[n_, p_] := First @ (Cases[FactorInteger[n], {p, e_} :> e] /. {} -> {0})

Then

f[60, 2]
f[60, 3]
f[60, 5]
f[60, 7]

2

1

1

0

f[11^17 13^15, 5]
f[11^17 13^15, 13]

0

15

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.