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
  • 2
    $\begingroup$ maybe f[n_, p_] := Cases[FactorInteger[n], {p, e_} :> e]? $\endgroup$
    – kglr
    Oct 28, 2016 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$ Oct 28, 2016 at 21:24

2 Answers 2

6
$\begingroup$

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

$\endgroup$
1
  • $\begingroup$ I can't believe I missed that. Again (yes, it's happened before). $\endgroup$ Oct 29, 2016 at 18:59
2
$\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 and acknowledge that you have read and understand our privacy policy and code of conduct.

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