Sphenic Number입니까?


29

Sphenic Number는 정확히 3 개의 소수로 구성된 숫자입니다. 처음 몇 개의 Sphenic 숫자는 30, 42, 66, 70, 78, 102, 105, 110, 114입니다. OEIS의 시퀀스 A007304 입니다.

당신의 작업 :

입력 된 정수가 Sphenic 숫자인지 판별하는 프로그램 또는 함수를 작성하십시오.

입력:

0과 10 ^ 9 사이의 정수이며, Sphenic Number 일 수도 있고 아닐 수도 있습니다.

산출:

입력이 Sphenic Number인지를 나타내는 참 / 거짓 값입니다.

예 :

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

채점 :

이것은 바이트 단위의 , 가장 짧은 코드입니다.


60sphenic 수는? 2 × 2 × 3 × 5
Outgolfer Erik

1
@EriktheOutgolfer는 3 개의 고유 소수의 곱이 아니며 3 개의 고유 한 소수와 1 개의 중복 소수의 곱입니다.
Rɪᴋᴇʀ

1
@Riker "3 개의 고유 한 소수"가 "모두 고유 한 3 개의 소수"를 의미하는지 또는 "유일 화 된 경우 3 개의 소수를 유지해야한다"는 것이 확실하지 않습니다. 편집 : 아, 나는 60sphenic 숫자가 아닙니다 참조하십시오 . (OP 설명을 기다리는 중)
Erik the Outgolfer

@EriktheOutgolfer sphenic 숫자의 정의에 따르면 60은 그중 하나가 아닙니다. 그러나이 도전에 60이 유효한지 모르겠습니다.
밀 마법사

@WheatWizard, 60은 스페 닉 숫자가 아닙니다 (예 : 출력 / 리턴 허위).
그리폰-복원 모니카

답변:


7

Brachylog , 6 3 바이트

ḋ≠Ṫ

온라인으로 사용해보십시오!

설명

ḋ        The prime factorization of the Input…
 ≠       …is a list of distinct elements…
  Ṫ      …and there are 3 elements

2
And then there's the one language which has a builtin like .
Erik the Outgolfer

And the builtin as well.
Zacharý

1
@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.
Fatalize

Congratulations on the shortest answer.
Gryphon - Reinstate Monica

11

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).


11

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

@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...
Luis Mendo

4
X= is the saddest builtin I've ever seen.
Erik the Outgolfer

9

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!


1
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.)
Mat


5

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


4

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.


4

Mathematica, 31 bytes

SquareFreeQ@#&&PrimeOmega@#==3&

Since you're already testing for squarefree-ness, PrimeNu will do just as well as PrimeOmega, and is shorter.
Mark S.

4

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.




2

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

Very nice use of ~: and #. An alternative could be (7&(=#.@~:@q:)~*) which I find a little easier to read, but is no shorter.
bob


2

Ruby, 81 49 46 bytes

Includes 6 bytes for command line options -rprime.

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

Try it online!


2

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!


You can check squarefreeness with k*k%n rather than n%k**2
xnor

Right, I only need one failure. Thanks!
Dennis

2

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 */

Does it answer the question, now?
Joel Rees

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.
Stephen

I'm here now, and I fixed my program, it's at 87 bytes now; but your program looks good too.
betseg

@betseg Interesting that you used floating point this time. Oh, and thanks for letting me borrow your algorithm. ;-)
Joel Rees

@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
betseg


1

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)}`)
}


1

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!



1

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"


This fails for input 60
Conor O'Brien

@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
Jonah

The last one was my original idea, and that fails for 8.
Conor O'Brien

I have (6=]#@,~.)@q: as a possible solution
Conor O'Brien

@ConorO'Brien ah good point about 8. yours will fail for 0, though.
Jonah

1

Japt, 14 bytes

k
k@è¥X ÉÃl ¥3

Try it online!


@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
Justin Mariner

Ah, you're right. I was just going by the test cases.
Oliver

@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.
Justin Mariner


1

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!


1

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.


1

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.


1
why not 3=#~.q: for 7characters? From a J session 3=#~.q: 30 ==> 1 and 3=#~.q: 20 ==> 0
Richard Donovan

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!
bob

0

Mathematica, 66 57 bytes

Length@#1==3&&And@@EqualTo[1]/@#2&@@(FactorInteger@#)&

Defines an anonymous function.

is Transpose.

Explanation

FactorInteger gives a list of pairs of factors and their exponents. E.g. FactorInteger[2250]=={{2,1},{3,2},{5,3}}. This is transposed for ease of use and fed to the function Length@#1==3&&And@@EqualTo[1]/@#2&. The first part, Length@#1==3, checks that there are 3 unique factors, while the second, And@@EqualTo[1]/@#2 checks that all the exponents are 1.


0

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


0

Python 99 bytes

def s(n):a,k=2,0;exec('k+=1-bool(n%a)\nwhile not n%a:n/=a;k+=10**9\na+=1\n'*n);return k==3*10**9+3

First submission. Forgive me if I did something wrong. Kinda silly, counts the number of factors of n, and then the number of times n is divisible by each (by adding 10**9).

I'm pretty sure there are a few easy ways to cut off ~10-20 characters, but I didn't.

Also this is intractably slow at 10**9. Could be made okay by changing '...a+=1\n'*n to '...a+=1\n'*n**.5, as we only need to go to the square root of n.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.