31
\$\begingroup\$

A Sphenic Number is a number that is the product of exactly three distinct primes. The first few Sphenic numbers are 30, 42, 66, 70, 78, 102, 105, 110, 114. This is sequence A007304 in the OEIS.

Your Task:

Write a program or function to determine whether an inputted integer is a Sphenic number.

Input:

An integer between 0 and 10^9, which may or may not be a Sphenic Number.

Output:

A truthy/falsy value indicating whether the input is a Sphenic Number.

Examples:

30  -> true
121 -> false
231 -> true
154 -> true
4   -> false
402 -> true
79  -> false
0   -> false
60  -> false
64  -> false
8   -> false
210 -> false

Scoring:

This is , shortest code in bytes wins.

\$\endgroup\$
9
  • \$\begingroup\$ Is 60 a sphenic number? 2 × 2 × 3 × 5 \$\endgroup\$ Jul 23, 2017 at 15:30
  • 1
    \$\begingroup\$ @EriktheOutgolfer that's not the product of 3 distinct primes though, that's the product of 3 distinct and 1 duplicate prime. \$\endgroup\$
    – Riker
    Jul 23, 2017 at 15:31
  • 1
    \$\begingroup\$ @Riker I'm not really sure if "3 distinct primes" means "3 primes that are all distinct" or "when uniquified there should remain 3 primes". EDIT: Oh I see, 60 isn't a sphenic number. (waiting for OP clarification) \$\endgroup\$ Jul 23, 2017 at 15:32
  • \$\begingroup\$ @EriktheOutgolfer According to the definition of sphenic numbers, 60 is not one of them. I do not know however if 60 is valid for this challenge. \$\endgroup\$
    – Wheat Wizard
    Jul 23, 2017 at 15:59
  • \$\begingroup\$ @WheatWizard, 60 is not a sphenic number (e.g. output/return falsy). \$\endgroup\$
    – Gryphon
    Jul 23, 2017 at 18:31

41 Answers 41

12
\$\begingroup\$

bash, 43 bytes

factor $1|awk '{print $2-$3&&$3-$4&&NF==4}'

Try it online!

Input via command line argument, outputs 0 or 1 to stdout.

Fairly self-explanatory; parses the output of factor to check that the first and second factors are different, the second and third are different (they're in sorted order, so this is sufficient), and there are four fields (the input number and the three factors).

\$\endgroup\$
1
  • \$\begingroup\$ You can remove the ` $1` because factor will take input from stdin if none is given on the command-line \$\endgroup\$
    – pxeger
    Mar 29, 2021 at 7:04
11
\$\begingroup\$

MATL, 7 bytes

_YF7BX=

Try it online! Or verify all test cases.

Explanation

_YF   % Implicit input. Nonzero exponents of prime-factor decomposition
7     % Push 7
B     % Convert to binary: gives [1 1 1] 
X=    % Is equal? Implicit display
\$\endgroup\$
2
  • \$\begingroup\$ @Suever I was thinking about that, but then falsy ouput becomes uglier (either empty with error or an array with some zeros). Not sure if I should... \$\endgroup\$
    – Luis Mendo
    Jul 23, 2017 at 16:02
  • 4
    \$\begingroup\$ X= is the saddest builtin I've ever seen. \$\endgroup\$ Jul 23, 2017 at 16:25
9
\$\begingroup\$

C, 88 78 126 58 77 73 + 4 (lm) = 77 bytes

l,j;a(i){for(l=1,j=0;l++<i;fmod(1.*i/l,l)?i%l?:(i/=l,j++):(j=9));l=i==1&&j==3;}

Ungolfed commented explanation:

look, div; //K&R style variable declaration. Useful. Mmm.

a ( num ) { // K&R style function and argument definitions.

  for (
    look = 1, div = 0; // initiate the loop variables.
    look++ < num;) // do this for every number less than the argument:

      if (fmod(1.0 * num / look, look))
      // if num/look can't be divided by look:

        if( !(num % look) ) // if num can divide look
          num /= look, div++; // divide num by look, increment dividers
      else div = 9;
      // if num/look can still divide look
      // then the number's dividers aren't unique.
      // increment dividers number by a lot to return false.

  // l=j==3;
  // if the function has no return statement, most CPUs return the value
  // in the register that holds the last assignment. This is equivalent to this:
  return (div == 3);
  // this function return true if the unique divider count is 3
}

Try it online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Consider i*1.0/l instead of the cast to float. (And since l,j are global they are initialized to 0 for free, you don't need to do that if the function is only called once. Not sure what the rule is for that.) \$\endgroup\$
    – Mat
    Jul 24, 2017 at 17:43
  • \$\begingroup\$ 76 bytes \$\endgroup\$
    – ceilingcat
    Dec 7, 2018 at 23:19
8
\$\begingroup\$

Brachylog, 6 3 bytes

ḋ≠Ṫ

Try it online!

Explanation

ḋ        The prime factorization of the Input…
 ≠       …is a list of distinct elements…
  Ṫ      …and there are 3 elements
\$\endgroup\$
4
  • 3
    \$\begingroup\$ And then there's the one language which has a builtin like . \$\endgroup\$ Jul 24, 2017 at 16:24
  • 1
    \$\begingroup\$ And the builtin as well. \$\endgroup\$
    – Adalynn
    Jul 25, 2017 at 18:17
  • 1
    \$\begingroup\$ @Zacharý is not really a built-in predicate though; it is a built-in variable: a list of 3 variable elements. It's a fairly useful pre-constrained variable in many different challenges. \$\endgroup\$
    – Fatalize
    Jul 26, 2017 at 6:33
  • \$\begingroup\$ Congratulations on the shortest answer. \$\endgroup\$
    – Gryphon
    Jul 28, 2017 at 11:56
5
\$\begingroup\$

CJam, 11 bytes

rimFz1=7Yb=

Try it online! Or verify all test cases.

Explanation

Based on my MATL answer.

ri    e# Read integer
mF    e# Factorization with exponents. Gives a list of [factor exponent] lists
z     e# Zip into a list of factors and a list of exponents
1=    e# Get second element: list of exponents
7     e# Push 7
Yb    e# Convert to binary: gives list [1 1 1]
=     e# Are the two lists equal? Implicitly display
\$\endgroup\$
0
5
\$\begingroup\$

Jelly, 8 bytes

ÆEḟ0⁼7B¤

Try it online!

Uses Luis Mendo's algorithm.

Explanation:

ÆEḟ0⁼7B¤
ÆE       Prime factor exponents
  ḟ0     Remove every 0
    ⁼7B¤ Equal to 7 in base 2?
\$\endgroup\$
0
5
\$\begingroup\$

Jelly, 6 bytes

ÆE²S=3

Try it online!

How it works

ÆE²S=3  Main link. Argument: n

ÆE      Compute the exponents of n's prime factorization.
  ²     Take their squares.
   S    Take the sum.
    =3  Test the result for equality with 3.
\$\endgroup\$
4
\$\begingroup\$

Husk, 6 bytes

≡ḋ3Ẋ≠p

Try it online!

Returns 1 for sphenic numbers and 0 otherwise.

Explanation

≡ḋ3Ẋ≠p    Example input: 30
     p    Prime factors: [2,3,5]
   Ẋ≠     List of absolute differences: [1,2]
≡         Is it congruent to...       ?
 ḋ3           the binary digits of 3: [1,1]

In the last passage, congruence between two lists means having the same length and the same distribution of truthy/falsy values. In this case we are checking that our result is composed by two truthy (i.e. non-zero) values.

\$\endgroup\$
4
\$\begingroup\$

Ruby, 81 49 46 bytes

Includes 6 bytes for command line options -rprime.

->n{n.prime_division.map(&:last)==[1]*3}

Try it online!

\$\endgroup\$
4
\$\begingroup\$

Mathematica, 31 bytes

SquareFreeQ@#&&PrimeOmega@#==3&
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Since you're already testing for squarefree-ness, PrimeNu will do just as well as PrimeOmega, and is shorter. \$\endgroup\$
    – Mark S.
    Jul 25, 2017 at 10:36
4
\$\begingroup\$

05AB1E, 7 5 bytes

ÓnO3Q

Try it online!

Uses Dennis's algorithm.

\$\endgroup\$
1
  • \$\begingroup\$ 3Q can be Í (pop a, push a-2) since only \$1\$ is truthy. \$\endgroup\$
    – Makonede
    Mar 21, 2021 at 18:59
2
\$\begingroup\$

Pyth, 9 bytes

&{IPQq3lP

Try it here.

\$\endgroup\$
2
\$\begingroup\$

Actually, 7 bytes

w♂N13α=

Try it online!

Explanation:

w♂N13α=
w       Push [prime, exponent] factor pairs
 ♂N     Map "take last element"
   1    Push 1
    3   Push 3
     α  Repeat
      = Equal?
\$\endgroup\$
2
\$\begingroup\$

Haskell, 59 bytes

f x=7==sum[6*0^(mod(div x a)a+mod x a)+0^mod x a|a<-[2..x]]

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Japt, 14 bytes

k
k@è¥X ÉÃl ¥3

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ @Oliver That would result in passing a function to Number.k(), which would have no effect and just check if the input has 3 prime factors, not 3 distinct prime factors. That would mean 8 (with three prime factors: 2, 2, 2) would pass despite not being in A007304 \$\endgroup\$ Jul 24, 2017 at 20:00
  • \$\begingroup\$ Ah, you're right. I was just going by the test cases. \$\endgroup\$
    – Oliver
    Jul 24, 2017 at 20:05
  • \$\begingroup\$ @Oliver Yeah, that really threw me for a loop when working on this solution. I just added 8 to the test cases for that reason. \$\endgroup\$ Jul 24, 2017 at 20:09
2
\$\begingroup\$

J, 15 bytes

7&(=2#.~:@q:)~*

Try it online!

Explanation

7&(=2#.~:@q:)~*  Input: integer n
              *  Sign(n)
7&(         )~   Execute this Sign(n) times on n
                 If Sign(n) = 0, this returns 0
          q:       Prime factors of n
       ~:@         Nub sieve of prime factors
    2#.            Convert from base 2
   =               Test if equal to 7
\$\endgroup\$
1
  • \$\begingroup\$ Very nice use of ~: and #. An alternative could be (7&(=#.@~:@q:)~*) which I find a little easier to read, but is no shorter. \$\endgroup\$
    – bob
    Jul 26, 2017 at 3:44
2
\$\begingroup\$

Dyalog APL, 26 bytes

⎕CY'dfns'
((≢,∪)≡3,⊢)3pco⎕

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Mathematica, 44 bytes

Plus@@Last/@#==Length@#==3&@FactorInteger@#&

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Python 3, 54 53 bytes

lambda n:sum(1>>n%k|7>>k*k%n*3for k in range(2,n))==6

Thanks to @xnor for golfing off 1 byte!

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ You can check squarefreeness with k*k%n rather than n%k**2 \$\endgroup\$
    – xnor
    Jul 24, 2017 at 5:50
  • \$\begingroup\$ Right, I only need one failure. Thanks! \$\endgroup\$
    – Dennis
    Jul 24, 2017 at 6:05
2
\$\begingroup\$

C, 91 102 bytes, corrected (again), golfed, and tested for real this time:

<strike>s(c){p,f,d;for(p=2,f=d=0;p<c&&!d;){if(c%p==0){c/=p;++f;if(c%p==0)d=1;}++p;}c==p&&f==2&&!d;}</strike>
s(c){int p,f,d;for(p=2,f=d=0;p<c&&!d;){if(c%p==0){c/=p;++f;if(c%p==0)d=1;}++p;}return c==p&&f==2&&!d;}

/* This also works in 93 bytes, but since I forgot about the standard rules barring default int type on dynamic variables, and about the not allowing implicit return values without assignments, I'm not going to take it:

p,f,d;s(c){for(p=2,f=d=0;p<c&&!d;){if(c%p==0){c/=p;++f;if(c%p==0)d=1;}++p;}p=c==p&&f==2&&!d;}

(Who said I knew anything about C? ;-)

Here's the test frame with shell script in comments:

/* betseg's program for sphenic numbers from 
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h> /* compile with -lm */

/* l,j;a(i){for(l=1,j=0;l<i;i%++l?:(i/=l,j++));l=i==1&&j==3;} */
#if defined GOLFED
l,j;a(i){for(l=1,j=0;l++<i;fmod((float)i/l,l)?i%l?:(i/=l,j++):(j=9));l=i==1&&j==3;}
#else 
int looker, jcount;
int a( intval ) {
  for( looker = 1, jcount = 0; 
    looker++ < intval; 
    /* Watch odd intvals and even lookers, as well. */
    fmod( (float)intval/looker, looker )  
      ? intval % looker /* remainder? */
        ? 0 /* dummy value */
        : ( inval /= looker, jcount++ /* reduce the parameter, count factors */ ) 
      : ( jcount = 9 /* kill the count */ ) 
  )
    /* empty loop */;
  looker = intval == 1 && jcount == 3; /* reusue looker for implicit return value */
}
#endif

/* for (( i=0; $i < 100; i = $i + 1 )) ; do echo -n at $i; ./sphenic $i ; done */

I borrowed betseg's previous answer to get to my version.

This is my version of betseg's algorithm, which I golfed to get to my solution:

/* betseg's repaired program for sphenic numbers
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int sphenic( int candidate )
{
  int probe, found, dups;
  for( probe = 2, found = dups = 0; probe < candidate && !dups; /* empty update */ ) 
  { 
    int remainder = candidate % probe;
    if ( remainder == 0 ) 
    {
      candidate /= probe;
      ++found;
      if ( ( candidate % probe ) == 0 )
        dups = 1;
    }
    ++probe;
  } 
  return ( candidate == probe ) && ( found == 2 ) && !dups;
}

int main( int argc, char * argv[] ) { /* Make it command-line callable: */
  int parameter;
  if ( ( argc > 1 ) 
       && ( ( parameter = (int) strtoul( argv[ 1 ], NULL, 0 ) ) < ULONG_MAX ) ) {
    puts( sphenic( parameter ) ? "true" : "false" );
  }
  return EXIT_SUCCESS; 
}

/* for (( i=0; $i < 100; i = $i + 1 )) ; do echo -n at $i; ./sphenic $i ; done */
\$\endgroup\$
7
  • \$\begingroup\$ Does it answer the question, now? \$\endgroup\$
    – Joel Rees
    Jul 24, 2017 at 11:42
  • \$\begingroup\$ Yes, it does. Insert this to link to betseg's answer: [betseg's answer](https://codegolf.stackexchange.com/a/135203/65836). You can also click edit on his answer to suggest an edit to it, if you want, that would include the explanation - no promises on whether it'll be approved or not. \$\endgroup\$
    – Stephen
    Jul 24, 2017 at 11:43
  • \$\begingroup\$ I'm here now, and I fixed my program, it's at 87 bytes now; but your program looks good too. \$\endgroup\$
    – betseg
    Jul 24, 2017 at 13:05
  • \$\begingroup\$ @betseg Interesting that you used floating point this time. Oh, and thanks for letting me borrow your algorithm. ;-) \$\endgroup\$
    – Joel Rees
    Jul 24, 2017 at 13:30
  • \$\begingroup\$ @JoelRees i added explanation to my answer, also your answer has a problem i think? it doesn't seem to work correctly: Try It Online \$\endgroup\$
    – betseg
    Jul 24, 2017 at 13:41
1
\$\begingroup\$

Javascript (ES6), 87 bytes

n=>(a=(p=i=>i>n?[]:n%i?p(i+1):[i,...p(i,n/=i)])(2)).length==3&&a.every((n,i)=>n^a[i+1])

Example code snippet:

f=
n=>(a=(p=i=>i>n?[]:n%i?p(i+1):[i,...p(i,n/=i)])(2)).length==3&&a.every((n,i)=>n^a[i+1])

for(k=0;k<10;k++){
  v=[30,121,231,154,4,402,79,0,60,64][k]
  console.log(`f(${v}) = ${f(v)}`)
}

\$\endgroup\$
1
\$\begingroup\$

Python 2, 135 121 bytes

  • Quite long since this includes all the procedures: prime-check, obtain-prime factors and check sphere number condition.
lambda x:(lambda t:len(t)>2and t[0]*t[1]*t[2]==x)([i for i in range(2,x)if x%i<1and i>1and all(i%j for j in range(2,i))])

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Python 2, 59 bytes

lambda x:6==sum(5*(x/a%a+x%a<1)+(x%a<1)for a in range(2,x))

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ This gives false positives like 48. I had been trying the same thing. \$\endgroup\$
    – xnor
    Jul 23, 2017 at 18:55
  • \$\begingroup\$ @xnor Fixed, but at the cost of bytes. \$\endgroup\$
    – Wheat Wizard
    Jul 23, 2017 at 19:07
1
\$\begingroup\$

J, 23 bytes

0:`((~.-:]*.3=#)@q:)@.*

Try it online!

Handling 8 and 0 basically ruined this one...

q: gives you all the prime factors, but doesn't handle 0. the rest of it just says "the unique factors should equal the factors" and "the number of them should be 3"

\$\endgroup\$
8
  • \$\begingroup\$ This fails for input 60 \$\endgroup\$ Jul 23, 2017 at 18:57
  • \$\begingroup\$ @ConorO'Brien thanks. See my edit -- fixing 60 helped, but i realized i also wasn't handling 0 correctly, and handling that more than doubles the bytes \$\endgroup\$
    – Jonah
    Jul 23, 2017 at 19:14
  • \$\begingroup\$ The last one was my original idea, and that fails for 8. \$\endgroup\$ Jul 23, 2017 at 19:21
  • \$\begingroup\$ I have (6=]#@,~.)@q: as a possible solution \$\endgroup\$ Jul 23, 2017 at 19:22
  • \$\begingroup\$ @ConorO'Brien ah good point about 8. yours will fail for 0, though. \$\endgroup\$
    – Jonah
    Jul 23, 2017 at 19:31
1
\$\begingroup\$

PHP, 66 bytes:

for($p=($n=$a=$argn)**3;--$n;)$a%$n?:$p/=$n+!++$c;echo$c==7&$p==1;

Run as pipe with -nR or try it online.

Infinite loop for 0; insert $n&& before --$n to fix.

breakdown

for($p=($n=$a=$argn)**3;    # $p = argument**3
    --$n;)                  # loop $n from argument-1
    $a%$n?:                     # if $n divides argument
        $p/=$n                      # then divide $p by $n
        +!++$c;                     # and increment divisor count
echo$c==7&$p==1;            # if divisor count is 7 and $p is 1, argument is sphenic

example
argument = 30:
prime factors are 2, 3 and 5
other divisors are 1, 2*3=6, 2*5=10 and 3*5=15
their product: 1*2*3*5*6*10*15 is 27000 == 30**3

\$\endgroup\$
1
\$\begingroup\$

VB.NET (.NET 4.5), 104 bytes

Function A(n)
For i=2To n
If n Mod i=0Then
A+=1
n\=i
End If
If n Mod i=0Then A=4
Next
A=A=3
End Function

I'm using the feature of VB where the function name is also a variable. At the end of execution, since there is no return statement, it will instead pass the value of the 'function'.

The last A=A=3 can be thought of return (A == 3) in C-based languages.

Starts at 2, and pulls primes off iteratively. Since I'm starting with the smallest primes, it can't be divided by a composite number.

Will try a second time to divide by the same prime. If it is (such as how 60 is divided twice by 2), it will set the count of primes to 4 (above the max allowed for a sphenic number).

Try It Online!

\$\endgroup\$
2
  • \$\begingroup\$ -2 bytes by using n\i=n/i instead of n Mod i=0. But is it fair to put Dim i as integer in the header when it's required for the function to work? Function A(n%) costs +1 byte. But if external Dim statements are allowed, then -7 bytes by pseudo-boolean arithmetic. \$\endgroup\$
    – Deadcode
    Mar 21, 2021 at 18:04
  • \$\begingroup\$ @Deadcode When I was writing it in Visual Studio, I didn't need to Dim i at all; I could use it directly in the loop. Putting it in the header was just to get the Mono implementation that Try It Online was using to compile. The shortening for Mod looks awesome though. I'll be sure to add that in! \$\endgroup\$
    – Brian J
    Mar 22, 2021 at 13:17
1
\$\begingroup\$

JavaScript (ES6), 80 bytes

n=>(p=(n,f=2)=>n%f?p(n,f+1):f,(a=p(n))<n&&(b=p(n/=a))<n&&(c=p(n/=b))==n&a<b&b<c)

Using a recursive function to get the smaller factor.
Output 1 if sphenic, false if there are 2 or less factors and 0 otherwise

Test

F=
n=>(p=(n,f=2)=>n%f?p(n,f+1):f,(a=p(n))<n&&(b=p(n/=a))<n&&(c=p(n/=b))==n&a<b&b<c)

;[30,121,231,154,4,402,79,0,60,64,8,210].forEach(
  x=>console.log(x,F(x))
)

\$\endgroup\$
1
\$\begingroup\$

Dyalog APL, 51 49 48 46 45 43 bytes

1∊((w=×/)∧⊢≡∪)¨(⊢∘.,∘.,⍨){⍵/⍨2=≢∪⍵∨⍳⍵}¨⍳w←⎕

Try it online! (modified so it can run on TryAPL)

I wanted to submit one that doesn't rely on the dfns namespace whatsoever, even if it is long.

\$\endgroup\$
1
\$\begingroup\$

J, 15 14 19 bytes

Previous attempt: 3&(=#@~.@q:)~*

Current version: (*/*3=#)@~:@q: ::0:

How it works:

(*/*3=#)@~:@q: ::0:  Input: integer n
               ::0:  n=0 creates domain error in q:, error catch returns 0
            q:       Prime factors of n
         ~:@         Nub sieve of prime factors 1 for first occurrence 0 for second
(*/*3=#)@            Number of prime factors is equal to 3, times the product across the nub sieve (product is 0 if there is a repeated factor or number of factors is not 3)

This passes for cases 0, 8 and 60 which the previous version didn't.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ why not 3=#~.q: for 7characters? From a J session 3=#~.q: 30 ==> 1 and 3=#~.q: 20 ==> 0 \$\endgroup\$ Jul 25, 2017 at 19:24
  • \$\begingroup\$ Richard, your suggestion gives a false positive for n=60 and creates a domain error for n=0, but my previous version failed for n=60 as well. Your comment prompted me to strive for a correct solution! \$\endgroup\$
    – bob
    Jul 26, 2017 at 3:14
1
\$\begingroup\$

Regex (ECMAScript), 46 bytes

^((?=(xx+?)\2*$)(?=(x+)(\3+$))\4(?!\2+$)){3}x$

Try it online!

This works similarly to Match strings whose length is a fourth power and very similarly to part of Is this a consecutive-prime/constant-exponent number:

^
(                   # Loop the following:
    (?=(xx+?)\2*$)  # \2 = smallest prime factor of tail
    (?=
        (x+)(\3+$)  # \3 = tail / {smallest prime factor of tail}; \4 = tool to make tail = \3
    )\4             # tail = \3
    (?!\2+$)        # assert that tail is no longer divisible by \2
){3}                # Execute the loop exactly 3 times
x$                  # assert tail == 1
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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