Recover the prime from the prime power

13

Definition: a prime power is a natural number that can be expressed in the form pn where p is a prime and n is a natural number.

Task: Given a prime power pn > 1, return the prime p.

Testcases:

input output
9     3
16    2
343   7
2687  2687
59049 3

Scoring: This is . Shortest answer in bytes wins.

Leaky Nun

Posted 2018-06-20T08:31:47.707

Reputation: 45 011

1Can n be 1? – user202729 – 2018-06-20T10:41:39.180

@user202729: In the 4th test-case n = 1. – Emigna – 2018-06-20T10:53:16.857

15Maybe it would have been more challenging to get the power part instead of the prime part. As it is, this is just "Get the lowest factor that isn't 1" – Jo King – 2018-06-20T13:48:14.967

Answers

13

Shakespeare Programming Language, 209 207 bytes

T.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:Listen tothy!Page:You cat!Scene V:.Page:You be the sum ofyou a cat!Be the product ofthe quotient betweenI you you worse I?If soLet usScene V.Open heart

Try it online!

(I/you)*you<I is shorter than I%you>0 in SPL.

user202729

Posted 2018-06-20T08:31:47.707

Reputation: 14 620

1The right tool for the job. – Jeremy Weirich – 2018-06-20T20:09:02.297

12

Emigna

Posted 2018-06-20T08:31:47.707

Reputation: 50 798

Are you sure that a list (or [] around the number) is a valid output? – Erik the Outgolfer – 2018-06-20T11:10:59.760

@EriktheOutgolfer: Relevant meta

– Emigna – 2018-06-20T11:19:05.493

Huh, didn't know about that, thanks. – Erik the Outgolfer – 2018-06-20T12:06:08.317

8

For those wondering, f = push list of prime factors (no duplicates)

– MCCCS – 2018-06-20T13:08:04.783

7

Java 8, 46 39 37 bytes

n->{int r=1;for(;n%++r>0;);return r;}

-7 bytes indirectly thanks to @Tsathoggua.
-2 bytes thanks to JoKing

Try it online.

Explanation:

n->{               // Method with integer as both parameter and return-type
  int r=1;         //  Start the result-integer `r` at 1
  for(;n%++r>0;);  //  Increase `r` by 1 before every iteration with `++r`
                   //  and loop until `n` is divisible by `r`
  return r;}       //  After the loop, return `r` as result

Kevin Cruijssen

Posted 2018-06-20T08:31:47.707

Reputation: 67 575

Following Luis Mendo's answer in python3, would it be possible to write n->{for(int i=1;++i<=n;)if(n%i<1)return i;} to get 43 characters? (I don't speak Java.)

– Tsathoggua – 2018-06-20T12:52:50.237

@Tsathoggua As you have it right now not, since Java methods must always have a return. n->{for(int i=1;++i<=n;)if(n%i<1)return i;return n;} would work, but is unfortunately longer. Java can have a single return in infinite loops however, which does indeed save bytes, so thanks! n->{for(int i=1;;)if(n%++i<1)return i;}. Since i will become n eventually (like with the test case 2687) and n%n==0, the i<=n isn't required in this case. – Kevin Cruijssen – 2018-06-20T13:14:58.713

1

How about 37 bytes. I'm not familiar enough with Java to see if any more can be golfed

– Jo King – 2018-06-20T13:30:12.533

@JoKing I don't see anything to golf further, so thanks for the -2. – Kevin Cruijssen – 2018-06-20T14:06:23.950

5

Python 3, 36 35 bytes

-1 byte thanks to mathmandan

f=lambda n,x=2:n%x and f(n,x+1)or x

Try it online!

Recursive function that finds the first factor larger than 1

Jo King

Posted 2018-06-20T08:31:47.707

Reputation: 38 234

1Nice. You can (usually) save a byte if you replace if/else with and/or. Like, f=lambda n,x=2:n%x and f(n,x+1)or x. – mathmandan – 2018-06-20T16:51:17.727

4

MATL, 4 3 bytes

Yfu

Try it online!

Explanation:

       % Implicit input:      [59049]
Yf     % Prime factorization: [3 3 3 3 3 3 3 3 3 3]
  u    % Unique elements:     [3]
       % Implicit output

Stewie Griffin

Posted 2018-06-20T08:31:47.707

Reputation: 43 471

1Very nice improvement! I would upvote again :-) – Luis Mendo – 2018-06-20T12:54:19.073

4

Octave, 16 bytes

@(x)factor(x)(1)

Try it online!

Explanation:

@(x)              % Anonymous function taking x as input
    factor(x)     % Prime factorization
             (1)  % Get the first element

Or:

@(x)max(factor(x))  % the makeup of makeup artists

Stewie Griffin

Posted 2018-06-20T08:31:47.707

Reputation: 43 471

1+1 for max factor – Brain Guider – 2018-06-20T16:48:19.963

4

Whitespace, 80 61 60 bytes

[S S T  T   N
_Push_-1][S S S N
_Push_0][T  N
T   T   _Read_STDIN_as_number][N
S S N
_Create_Label_LOOP][S S S T N
_Push_1][T  S S T   _Subtract][S N
S _Duplicate][S S S N
_Push_0][T  T   T   _Retrieve][S N
T   _Swap][T    S T T   _Modulo][N
T   T   N
_If_0_Jump_to_Label_LOOP][S S T T   N
_Push_-1][T S S N
_Multiply][T    N
S T _Print_as_number]

-20 bytes thanks to @JoKing.

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Explanation in pseudo-code:

Integer n = STDIN as integer
Integer i = -1
Start LOOP:
  i = i - 1
  if(n modulo-i is negative)
    Go to next iteration of LOOP
  else
    i = i * -1
    Print i
    Exit with error: No exit defined

Example run: input = 9

Command   Explanation                    Stack        Heap     STDIN    STDOUT    STDERR

SSTTN     Push -1                        [-1]
SSSN      Push 0                         [-1,0]
TNTT      Read STDIN as integer          [-1]         {0:9}    9
NSSN      Create Label_LOOP              [-1]         {0:9}
 SSSTN    Push 1                         [-1,1]       {0:9}
 TSST     Subtract top two (-1-1)        [-2]         {0:9}
 SNS      Duplicate top (-2)             [-2,-2]      {0:9}
 SSSN     Push 0                         [-2,-2,0]    {0:9}
 TTT      Retrieve                       [-2,-2,9]    {0:9}
 SNT      Swap top two                   [-2,9,-2]    {0:9}
 TSTT     Modulo top two (9%-2)          [-2,-1]      {0:9}
 NTSN     If neg.: Jump to Label_LOOP    [-2]         {0:9}

 SSTTN    Push -1                        [-2,-1]      {0:9}
 TSST     Subtract top two (-2-1)        [-3]         {0:9}
 SNS      Duplicate top (-2)             [-3,-3]      {0:9}
 SSSN     Push 0                         [-3,-3,0]    {0:9}
 TTT      Retrieve                       [-3,-3,9]    {0:9}
 SNT      Swap top two                   [-3,9,-3]    {0:9}
 TSTT     Modulo top two (9%-3)          [-3,0]       {0:9}
 NTSN     If neg.: Jump to Label_LOOP    [-3]         {0:9}
 SSTTN    Push -1                        [-3,-1]      {0:9}
 TSSN     Multiply top two (-3*-1)       [3]          {0:9}
 TNST     Print as integer               []           {0:9}             3
                                                                                  error

Program stops with an error: No exit found.

Kevin Cruijssen

Posted 2018-06-20T08:31:47.707

Reputation: 67 575

1Do you need the i == n check? n%n would be 0 anyway – Jo King – 2018-06-20T11:03:49.007

@JoKing Ah, of course. Thanks, 19 bytes saved right there. :) – Kevin Cruijssen – 2018-06-20T11:07:43.833

Could you only loop if not n%i and call the print afterwards? – Jo King – 2018-06-20T11:12:35.790

1@JoKing I'm pretty sure not. Whitespace doesn't really have loops, it just has jumps to labels. The only three options I have is to: 1. jump to a certain label unconditionally; 2. jump to a certain label if the top of the stack is 0; 3. jump to a certain label if the top of the stack is negative. Unfortunately there isn't a "jump to label if positive" to continue the loop. I could accomplish this by multiplying by -1 before checking for negative, but I doubt that will be shorter. – Kevin Cruijssen – 2018-06-20T11:15:16.613

1

Tried to do it with a negative modulus and ended up at <s>62</s>60 bytes (yay). Turns out you can't store at negative heap addresses (though 0 saved a couple of bytes)

– Jo King – 2018-06-20T12:35:13.920

@JoKing Thanks again! Yes, I tried saving an input in a negative heap address before, but unfortunately that doesn't work. Also, TIO works as intended with negative modulo, but apparently vii5ard which I usually use to develop in (easier to debug and see all commands) will give 9%-2 = 1 instead of -1. But I use TIO as lead in my Whitespace answers, which works completely fine. Well done!

– Kevin Cruijssen – 2018-06-20T13:07:45.340

3

Funky, 30 bytes

n=>fori=2n>i i++if1>n%i breaki

Try it online!

ATaco

Posted 2018-06-20T08:31:47.707

Reputation: 7 898

0== can be 1> I think. – Kevin Cruijssen – 2018-06-20T09:09:10.230

2

JavaScript (ES6), 25 bytes

f=(n,k=2)=>n%k?f(n,k+1):k

Try it online!

Arnauld

Posted 2018-06-20T08:31:47.707

Reputation: 111 334

2

Jelly, 3 bytes

ÆfḢ

Try it online!

ÆfṪ, ÆfX could also be seriously competing functions.
ÆfQ could be a seriously competing full program.

Erik the Outgolfer

Posted 2018-06-20T08:31:47.707

Reputation: 38 134

2

C (gcc), 28 bytes

f(k,p){for(p=1;k%++p;);k=p;}

Try it online!

Jonathan Frech

Posted 2018-06-20T08:31:47.707

Reputation: 6 681

2

Forth (gforth), 34 bytes

: f 1 begin 1+ 2dup mod 0= until ;

Try it online!

Explanation

  1. Iterate integers starting from 2
  2. Stop and return when you find one that divides n with no remainder

Code Explanation

: f               \ Define a new word
  1               \ place a 1 on the stack (to use as a counter/index)
  begin           \ start indefinite loop
    1+ 2dup       \ increment counter and duplicate counter and prime power
    mod           \ calculate power % index
  0= until        \ end the loop if modulus is 0 (no remainder)
;                 \ end word definition

reffu

Posted 2018-06-20T08:31:47.707

Reputation: 1 361

1

Pyth, 2 bytes

hP

Try it here!

Mr. Xcoder

Posted 2018-06-20T08:31:47.707

Reputation: 39 774

1

Brachylog, 2 bytes

ḋh

Try it online!

Explanation

ḋ       Prime decomposition
 h      Head

Fatalize

Posted 2018-06-20T08:31:47.707

Reputation: 32 976

1

J, 4 bytes

0{q:

Select { the first 0 of the prime factors q:

Try it online!

Galen Ivanov

Posted 2018-06-20T08:31:47.707

Reputation: 13 815

1

Okx

Posted 2018-06-20T08:31:47.707

Reputation: 15 025

U+1D414 is one character, but in UTF-8 and UTF-16 this is represented by 4 bytes. – Ruud Helderman – 2018-06-21T11:06:52.083

1@RuudHelderman Correct, but this isn't in UTF-8 nor UTF-16. – Okx – 2018-06-21T14:28:06.700

1

@RuudHelderman You may want to see Neim codepage.

– JungHwan Min – 2018-06-21T16:09:53.983

@JungHwanMin Thanks; browsing Okx's earlier Neim submissions, I noticed my slightly ignorant reaction wasn't the first. Clever feature, but far from obvious; warrants explanation (as done here). Quoting code-golf tag info: "Unless the question is specified to be scored by characters, it is scored by bytes. If it doesn't specify a character encoding to use for scoring, answers which use Unicode code points outside 0 to 255 should state the encoding used."

– Ruud Helderman – 2018-06-21T19:20:44.667

@RuudHelderman per meta consensus, if an answer does not specify an encoding, it defaults to the language's default encoding. If that doesn't exist, then it is UTF-8. In this case, Neim has a defined default encoding, so it is assumed to be the encoding of the answer, without the answerer having to explain as such.

– JungHwan Min – 2018-06-21T22:06:56.110

1

R, 32 26 bytes

@Giuseppe with different logic and a shorter solution:

(x=2:(n=scan()))[!n%%x][1]

Try it online!

Original:

numbers::primeFactors(scan())[1]

Try it online!

This is obviously a much superior port of the 05AB1E solution.

ngm

Posted 2018-06-20T08:31:47.707

Reputation: 3 974

1

Haskell, 26 bytes

f n=until((<1).mod n)(+1)2

Try it online!

xnor

Posted 2018-06-20T08:31:47.707

Reputation: 115 687

1

Mathematica, 17 bytes

Divisors[#][[2]]&

The second smallest divisor.

for Monica

Posted 2018-06-20T08:31:47.707

Reputation: 1 172

0

ARBLE, 19 bytes

index(factors(a),1)

Try it online!

ATaco

Posted 2018-06-20T08:31:47.707

Reputation: 7 898

0

Japt -g, 1 byte

k

Try it here

Shaggy

Posted 2018-06-20T08:31:47.707

Reputation: 24 623

0

Python 3, 47 45 44 bytes

Inspired by Kevin Cruijssen's answer in Java.

2 3 bytes removed thanks to Jo King.

lambda n:[i+1for i in range(n)if n%-~i<1][1]

Try it online!

Luis Mendo

Posted 2018-06-20T08:31:47.707

Reputation: 87 464

1You have an extra space before the if, and the condition can be <1 – Jo King – 2018-06-20T10:31:02.847

1

You can save one byte by doing range(n) and incrementing i in place

– Jo King – 2018-06-20T23:04:54.497

0

PowerShell, 31 bytes

param($a)(2..$a|?{!($a%$_)})[0]

Try it online!

Constructs a range from 2 to input $a, pulls out those elements where (?) the modulo operation % results in a zero !(...) (i.e., those that are divisors of $a), and then takes the smallest [0] one thereof. That's left on the pipeline, output is implicit.

AdmBorkBork

Posted 2018-06-20T08:31:47.707

Reputation: 41 581

0

Visual Basic .NET (.NET Framework v4.5), 123 71 bytes

-52 bytes thanks to @Jo King

Function A(n)
For i=n To 2 Step-1
A=If(n Mod i=0,i,A)
Next
End Function

Try it online!

Ungolfed:

Function A(input As Long) As Long
    For i = input To 2 Step -1
        A = If (input Mod i = 0, i, A)
    Next
End Function

Explanation:

The i loop searches backwards from the first number, and finds all numbers that divide it evenly. Because we are going backwards, the smallest is stored in the vairable A.

VB gives you a free variable that matches your function name (in my case, A). At the end of the function execution, the value in that variable is returned (barring an explicit Return statement.

Brian J

Posted 2018-06-20T08:31:47.707

Reputation: 653

1You don't need the prime check at all. The smallest factor of a number (other than 1) is guaranteed to be a prime, otherwise there would be a smaller factor – Jo King – 2018-06-20T13:54:27.603

@JoKing D'oh! Of course, can't believe I missed that. Thanks! – Brian J – 2018-06-20T13:55:40.613

0

Perl 6, 22 bytes

{grep($_%%*,2..$_)[0]}

Try it online!

Anonymous code block that filters the factors of the range of 2 to the input and returns the first one. I tried using ^$ to save 2 bytes, but that didn't work in the case that the input was prime.

Jo King

Posted 2018-06-20T08:31:47.707

Reputation: 38 234

0

Haskell, 29 bytes

f y=[x|x<-[2..],mod y x<1]!!0

Try it online!

Post Rock Garf Hunter

Posted 2018-06-20T08:31:47.707

Reputation: 55 382

0

Pari/GP, 17 bytes

n->factor(n)[1,1]

Try it online!


Pari/GP, 17 bytes

n->divisors(n)[2]

Try it online!

alephalpha

Posted 2018-06-20T08:31:47.707

Reputation: 23 988

0

Ruby, 100 bytes

require"prime"
i=gets.to_i
Prime.each(i){|p|(1..i).each{|n|c=p**n==i
    puts p if c
    exit if c}}

Try it online!

Alex Allen

Posted 2018-06-20T08:31:47.707

Reputation: 91

0

Stax, 3 bytes

|fh

Run and debug it

First element of prime factorization.

wastl

Posted 2018-06-20T08:31:47.707

Reputation: 3 089

0

Julia 0.6, 25 bytes

n->[2:n;][n.%(2:n).<1][1]

Try it online!

sundar - Reinstate Monica

Posted 2018-06-20T08:31:47.707

Reputation: 5 296

0

Ruby, 26 bytes

->n,i=1{(1>n%i+=1)?i:redo}

Try it online!

Reinstate Monica -- notmaynard

Posted 2018-06-20T08:31:47.707

Reputation: 1 053

0

QBasic, 39 bytes

INPUT x
p=2
WHILE x\p<x/p
p=p+1
WEND
?p

Trial division; finds the first factor greater than 1, which is guaranteed to be the prime factor.

The only trick here is the condition x\p<x/p, which uses integer vs. floating point division to test whether "x is not divisible by p." See this tip for details.

DLosc

Posted 2018-06-20T08:31:47.707

Reputation: 21 213