它是一个折数字吗?


29

幻数是一个正好是三个不同素数的乘积。前几个Sphenic数字为30, 42, 66, 70, 78, 102, 105, 110, 114。这是OEIS中的序列A007304

你的任务:

编写程序或函数以确定输入的整数是否为Sphenic数字。

输入:

0到10 ^ 9之间的整数,可以是也可以不是幻数。

输出:

真/假值,指示输入是否为幻数。

例子:

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

得分:

这是,以字节为单位的最短代码获胜。


60一个斜数?2 × 2 × 3 × 5
暴民埃里克'17

1
@EriktheOutgolfer不是3个不同素数的乘积,而是3个不同素数和1个重复素数的乘积。
Rɪᴋᴇʀ

1
@Riker我不太确定“ 3个不同的素数”是指“ 3个完全不同的素数”还是“统一时应保留3个素数”。编辑:哦,我知道,60这不是一个斜数。(等待OP澄清)
越野选手埃里克(Erik the Outgolfer

@EriktheOutgolfer根据斜数字的定义,60不是其中之一。但是,我不知道60是否对这个挑战有效。
小麦巫师

@ WheatWizard,60不是一个连字符(例如,输出/返回错误)。
狮ry-恢复莫妮卡

Answers:


7

Brachylog6 3个字节

ḋ≠Ṫ

在线尝试!

说明

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

2
然后是一种语言,其内置像
暴民埃里克(Erik the Outgolfer)

以及内置的
扎卡里

1
@Zacharý 并不是一个真正的内置谓词。它是一个内置变量:3个变量元素的列表。在许多不同的挑战中,这是一个相当有用的预约束变量。
Fatalize

恭喜您回答最短。
狮phon-恢复莫妮卡

11

bash,43个字节

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

在线尝试!

通过命令行参数输入,输出01到标准输出。

不言自明;解析的输出factor以检查第一个和第二个因子是否不同,第二个和第三个因子是否不同(它们的排序顺序,因此就足够了),并且有四个字段(输入数和三个因子)。


11

MATL,7个字节

_YF7BX=

在线尝试!验证所有测试用例

说明

_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我曾在考虑这个问题,但后来虚假的输出变得更难看(要么为空且有错误,要么为一个带有零的数组)。不知道我是否应该...
Luis Mendo

4
X=是我见过的最可悲的内置物。
暴民埃里克(Erik the Outgolfer)

9

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

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;}

取消评论的解释:

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
}

在线尝试!


1
考虑i*1.0/l而不是强制浮动。(既然lj是全球它们被初始化为0免费的,你不需要做,如果函数只调用一次不知道规则是什么那。)


5

CJam,11个字节

rimFz1=7Yb=

在线尝试!验证所有测试用例

说明

根据我的MATL答案。

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

外壳,6个字节

≡ḋ3Ẋ≠p

在线尝试!

对于大数返回1,否则返回0。

说明

≡ḋ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]

在最后一段中,两个列表之间的全等意味着具有相同的长度和相同的真实/虚假值分布。在这种情况下,我们正在检查我们的结果是否由两个真实(即非零)值组成。


4

Mathematica,31个字节

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

由于您已经在测试方空度,PrimeNu因此效果PrimeOmega和一样好,并且更短。
Mark S.

4

果冻,6个字节

ÆE²S=3

在线尝试!

怎么运行的

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.