这是史密斯号码吗?


28

挑战说明

史密斯号码是一个复合数字,其数字之和等于的质因子数字之和的总和。给定一个整数N,确定它是否是史密斯数。

最初的几个史密斯数字是42227588594121166202265274319346355378382391438(序列A006753在OEIS)。

样本输入/输出

18: False (sum of digits: 1 + 8 = 9; factors: 2, 3, 3; sum of digits of factors: 2 + 3 + 3 = 8)
22: True
13: False (meets the digit requirement, but is prime)
666: True (sum of digits: 6 + 6 + 6 = 18; factors: 2, 3, 3, 37; sum of digits of factors: 2 + 3 + 3 + 3 + 7 = 18)
-265: False (negative numbers can't be composite)
0: False (not composite)
1: False (not composite)
4937775: True

笔记

  • 您的代码可以是函数(方法)或完整的程序,
  • 而不是像的话TrueFalse,你可以使用任何truthy和falsy值,只要很清楚它们是什么,
  • 这是一个挑战,所以请使您的代码尽可能短!

6
我必须读过这篇文章:“数位之和等于其主要因子的数位之和”几次:P
Stewie Griffin

@StewieGriffin:是的,这是一个相当复杂的句子,但是我觉得我需要给出一个适当的定义,而不是仅仅依靠示例:)
shooqie

2
这是我认为“ Java + this = no”的问题之一,尽管如此,我还是提出了这个建议:P
Shaun Wild

3
我有时会注意到数字,数字总和等模式,但实际上,人们是否注意到这样的东西:“阿尔伯特·威兰斯基(Albert Wilansky)注意到史密斯(Smith)数字这个词是因为他注意到了他姐夫电话号码中的定义属性”
Stewie Griffin

1
@StewieGriffin:是的,就像Ramanujan和1729,也总是让我感到困惑。
shooqie '16

Answers:


9

果冻12 11 字节

Æfḟȯ.DFżDSE

对于Smith编号,返回1,否则返回0在线尝试!验证所有测试用例

背景

Æf实现(素数分解)和D(整数至小数),以便P(乘积)和(整数至小数)构成左逆。

对于-44的整数,Æf返回以下内容。

-4 -> [-1, 2, 2]
-3 -> [-1, 3]
-2 -> [-1, 2]
-1 -> [-1]
 0 -> [0]
 1 -> []
 2 -> [2]
 3 -> [3]
 4 -> [2, 2]

对于数字-10,-1,-0.5、0、0.5、1、10D返回以下内容。

-11   -> [-1, -1]
-10   -> [-1, 0]
 -1   -> [-1]
 -0.5 -> [-0.5]
  0   -> [0]
  0.5 -> [0.5]
  1   -> [1]
 10   -> [1, 0]
 11   -> [1, 1]

怎么运行的

Æfḟȯ.DFżDSE  Main link. Argument: n (integer)

Æf           Yield the prime factorization of n.
  ḟ          Filter; remove n from its prime factorization.
             This yields an empty array if n is -1, 0, 1, or prime.
   ȯ.        If the previous result is an empty array, replace it with 0.5.
     D       Convert all prime factors to decimal.
      F      Flatten the result.
        D    Yield n in decimal.
       ż     Zip the results to both sides, creating a two-column array.
         S   Compute the sum of each column.
             If n is -1, 0, 1, or prime, the sum of the prime factorization's
             digits will be 0.5, and thus unequal to the sum of the decimal array.
             If n < -1, the sum of the prime factorization's digits will be
             positive, while the sum of the decimal array will be negative.
          E  Test both sums for equality.

2
我不得不说这是一个非常酷的解决方案!
Emigna '16

@Emigna-这就是我所做的,但是以非常出色的方式实现了:D
Jonathan Allan

@JonathanAllan不幸的是,我不会说Jelly,所以我不知道您的代码是什么:)
Emigna

1
@Emigna-是的,我计划在添加“如何工作”部分之前先弄清楚如何打高尔夫球。
乔纳森·艾伦

9

Python 2,122 115 110 106字节

n=m=input()
s=0
for d in range(2,n):
 while n%d<1:n/=d;s+=sum(map(int,`d`))
print n<m>s==sum(map(int,`m`))

由于丹尼斯节省了4个字节

在ideone.com上尝试

说明

在stdin上读取一个数字,并输出True该数字是否为史密斯数字False

n=m=input()                  # stores the number to be checked in n and in m
s=0                          # initializes s, the sum of the sums of digits of prime factors, to 0
for d in range(2,n):         # checks all numbers from 2 to n for prime factors
 while n%d<1:                # while n is divisible by d
                             #   (to include the same prime factor more than once)
  n/=d                       # divide n by d
  s+=sum(map(int,`d`))       # add the sum of the digits of d to s
print                        # print the result: "True" if and only if
      n<m                    #   n was divided at least once, i.e. n is not prime
      >                      #   and m>s (always true) and
      s==sum(map(int,`m`))   #   s is equal to the sum of digits of m (the input)

1
向下选民-这可能是有用的添加评论,解释为什么
乔纳森·艾伦

6
@JonathanAllan编辑答案时,社区用户自动投下了下降票。我认为这是一个错误
丹尼斯

1
最后一行可以重写为print n<m>s==sum(map(int,`m`))
丹尼斯

@Dennis链式比较非常有用!
LevitatingLion

8

Brachylog,19个字节

@e+S,?$pPl>1,P@ec+S

在线尝试!

说明

@e+S,                 S is the sum of the digits of the input.
     ?$pP             P is the list of prime factors of the input.
        Pl>1,         There are more than 1 prime factors.
             P@e      Split each prime factor into a list of digits.
                c     Flatten the list.
                 +S   The sum of this list of digits must be S.

2
@JonathanAllan 确实如此。在Brachylog中,数字的负号是_(所谓的低负号)。
致命

7

05AB1E11 17字节

X›0si¹ÒSO¹SOQ¹p_&

说明

X›0si              # if input is less than 2 then false, else
       SO          # sum of digits
     ¹Ò            # of prime factors with duplicates
            Q      # equal to
          SO       # sum of digits
         ¹         # of input
                &  # and
             ¹p_   # input is not prime

在线尝试!


5

PowerShell v3 +,183字节

param($n)$b=@();for($a=$n;$a-gt1){2..$a|?{'1'*$_-match'^(?!(..+)\1+$)..'-and!($a%$_)}|%{$b+=$_;$a/=$_}}$n-notin$b-and(([char[]]"$n")-join'+'|iex)-eq(($b|%{[char[]]"$_"})-join'+'|iex)

没有内置的素数检查。无内置保理。无内置数字总和。一切都是手工制作的。:D

将输入$n作为整数,设置为$b等于空数组。这$b是我们收集的主要因素。

接下来是一个for循环。我们首先设置$a等于我们的输入数字,条件是直到$a小于或等于1。此循环将查找我们的主要因素。

我们从环路2最多$a,用途Where-Object|?{...})退出素数,同时也是因素!($a%$_)。这些因素被送入一个内部循环|%{...},该循环将因子放入$b并进行除法$a(因此我们最终将了解1)。

因此,现在我们拥有所有主要因素$b。是时候编写布尔输出了。我们需要验证$n-notin $b,因为如果是,则表示$n是质数,因此不是史密斯数。另外,(-and)我们需要确保我们的两组数字总和-equal。结果布尔值保留在管道上,并且输出是隐式的。

注意-notin运营商需要v3或更高版本。我仍在运行输入4937775(计算速度),因此在完成输入后将对其进行更新。3个多小时后,出现了stackoverflow错误。因此,在某处存在一些上限。那好吧。

这将适用于负输入,零或一,因为在-and尝试计算数字总和(如下所示)时,右手将阻止错误,这将导致一半$false在求值时用到。由于默认情况下忽略 STDERR ,并且仍然显示正确的输出,所以可以。


测试用例

PS C:\Tools\Scripts\golfing> 4,22,27,58,85,94,18,13,666,-265,0,1|%{"$_ -> "+(.\is-this-a-smith-number.ps1 $_)}
4 -> True
22 -> True
27 -> True
58 -> True
85 -> True
94 -> True
18 -> False
13 -> False
666 -> True
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Tools\Scripts\golfing\is-this-a-smith-number.ps1:1 char:179
+ ... "$_"})-join'+'|iex)
+                    ~~~
    + CategoryInfo          : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand

-265 -> False
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Tools\Scripts\golfing\is-this-a-smith-number.ps1:1 char:179
+ ... "$_"})-join'+'|iex)
+                    ~~~
    + CategoryInfo          : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand

0 -> False
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Tools\Scripts\golfing\is-this-a-smith-number.ps1:1 char:179
+ ... "$_"})-join'+'|iex)
+                    ~~~
    + CategoryInfo          : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand

1 -> False


3

果冻27 25 23 字节

(进一步高尔夫可能 绝对可能的)

ḢDS×
ÆFÇ€SḢ
DS=Ça<2oÆP¬

返回0False或1True

TryItOnline的所有测试用例

怎么样?

DS=Ça<2oÆP¬ - main link takes an argument, n
DS          - transform n to a decimal list and sum up
   Ç        - call the previous link (ÆFÇ€SḢ)
  =         - test for equality
     <2     - less than 2?
    a       - logical and
        ÆP  - is prime?
       o    - logical or
          ¬ - not
            - all in all tests if the result of the previous link is equal to the digit
              sum if the number is composite otherwise returns 0.

ÆFÇ€SḢ - link takes an argument, n again
ÆF     - list of list of n's prime factors and their multiplicities
  Ç€   - apply the previous link (ḢDS×) for each
    S  - sum up
     Ḣ - pop head of list (there will only be one item)

ḢDS× - link takes an argument, a factor, multiplicity pair
Ḣ    - pop head, the prime factor - modifies list leaving the multiplicity
 DS  - transform n to a decimal list and sum up
   × - multiply the sum with the multiplicity

3

其实是18个位元组

不幸的是,实际上并没有内置因数分解的功能,它可以将数量的主要因素赋予多重性,因此我不得不一起破解。欢迎打高尔夫球。在线尝试!

;w`i$n`MΣ♂≈Σ@$♂≈Σ=

开球

         Implicit input n.
;w       Duplicate n and get the prime factorization of a copy of n.
`...`M   Map the following function over the [prime, exponent] lists of w.
  i        Flatten the list. Stack: prime, exponent.
  $n       Push str(prime) to the stack, exponent times.
            The purpose of this function is to get w's prime factors to multiplicity.
Σ        sum() the result of the map.
          On a list of strings, this has the same effect as "".join()
♂≈Σ      Convert every digit to an int and sum().
@        Swap the top two elements, bringing other copy of n to TOS.
$♂≈Σ     Push str(n), convert every digit to an int, and sum().
=        Check if the sum() of n's digits is equal 
          to the sum of the sum of the digits of n's prime factors to multiplicity.
         Implicit return.

3

Haskell中,120个 105字节

1%_=[];a%x|mod a x<1=x:div a x%x|0<1=a%(x+1)
p z=sum[read[c]|c<-show z]
s x|z<-x%2=z<[x]&&sum(p<$>z)==p x

2

八度,80 78字节

t=num2str(factor(x=input('')))-48;disp(any(t<0)&~sum([num2str(x)-48 -t(t>0)]))

说明:

factor(x=input(''))                 % Take input, store as x and factor it
num2str(factor(x=input('')))-48     % Convert it to an array (123 -> [1 2 3]) 
                                    % and store as t
any(t<0)                            % Check if there are several prime factors
                                    % [2 3] -> [2 -16 3]
sum([num2str(x)-48 -t(t>0)])        % Check if sum of prime factor
                                    % is equal the sum of digits

在线尝试。


1
any(t<0)对于非素性非常巧妙
路易斯Mendo

2

Pyth,21个字节

&&>Q1!P_QqsjQTssmjdTP

接受整数输入并打印TrueFalse相关的程序。

在线尝试

怎么运行的

&&>Q1!P_QqsjQTssmjdTP  Program. Input: Q
           jQT         Yield digits of the base-10 representation of Q as a list
          s            Add the digits
                    P  Yield prime factors of Q (implicit input fill)
                mjdT   Map base-10 representation across the above, yielding digits of each
                       factor as a list of lists
               s       Flatten the above
              s        Add up the digits
         q             Those two sums are equal
&                      and
  >Q1                  Q>1
 &                     and
     !P_Q              Q is not prime
                       Implicitly print

2

Perl 6的92个 88 87字节

{sub f(\i){my \n=first i%%*,2..i-1;n??n~f i/n!!i}
!.is-prime&&$_>1&&.comb.sum==.&f.comb.sum}

{sub f(\i){my \n=first i%%*,2..^i;n??[n,|f i/n]!!|i}
$_>.&f>1&&.comb.sum==.&f.comb.sum}

返回布尔的匿名函数。

  • 现在进行100%手动分解和素数检查。
  • 因为m> Ω(m),所以通过一次链比较来测试“输入> 1”和“因子数> 1”,从而节省了一些字节。

在线尝试

编辑:-1字节感谢b2gills


2..i-1最好拼写为2..^i
布拉德·吉尔伯特b2gills

2

Java 7中,509个 506 435 426 419 230字节

boolean c(int n){return n<2|p(n)?0>1:d(n)==f(n);}int d(int n){return n>9?n%10+d(n/10):n;}int f(int n){int r=0,i;for(i=1;++i<=n;)for(;n%i<1;n/=i,r+=i>9?d(i):i);return r;}boolean p(int n){int i=2;while(i<n)n=n%i++<1?0:n;return n>1;}

我应该已经听过@BasicallyAlanTuring的评论。

这是我认为“ Java + this = no”的问题之一,尽管如此,我还是赞成这个想法:P

嗯..有些编程语言将一个字节用于素数或素数检查,但是Java当然不是其中之一。

编辑:现在我有一些时间考虑它减少了一半的字节数。

脱节(分拣..)和测试用例:

在这里尝试。

class M{
  static boolean c(int n){
    return n < 2 | p(n)
            ? 0 > 1 //false
            : d(n) == f(n);
  }

  // Sums digits of int
  static int d(int n) {
    return n > 9
            ? n%10 + d(n/10)
            : n;
  }

  // Convert int to sum of prime-factors
  static int f(int n) {
    int r = 0,
        i;
    for(i = 1; ++i <= n; ){
      for( ; n % i < 1; n /= i,
                        r += i > 9 ? d(i) : i);
    }
    return r;
  }

  // Checks if the int is a prime
  static boolean p(int n){
    int i = 2;
    while(i < n){
      n = n % i++ < 1
           ? 0
           : n;
    }
    return n > 1;
  }

  public static void main(String[] a){
    System.out.println(c(18));
    System.out.println(c(22));
    System.out.println(c(13));
    System.out.println(c(666));
    System.out.println(c(-256));
    System.out.println(c(0));
    System.out.println(c(1));
    System.out.println(c(4937775));
  }
}

输出:

false
true
false
true
false
false
false
true

2

Brachylog(较新),11个字节

¬ṗ&ẹ+.&ḋcẹ+

在线尝试!

如果输入是史密斯编号,则谓词成功,如果输入不是,则谓词失败。

               The input
¬ṗ             is not prime,
  &            and the input's 
   ẹ           digits
    +          sum to
     .         the output variable,
      &        and the input's 
       ḋ       prime factors' (getting prime factors of a number < 1 fails)
        c      concatenated
         ẹ     digits
          +    sum to
               the output variable.


2

JavaScript(ES6), 87 86  84字节

m=>(i=2,S=0,g=n=>([...i+''].map(v=>s-=v,s=S),i-m?n%i?g(n,i++):g(n/i,S=s):s==2*S))(m)

在线尝试!


1

Pyke,16个字节

Pm[`mbs(sQ[qRlt*

在这里尝试!


1
输入结果不足而导致的错误小于2
Jonathan Allan

@JonathanAllan没有输出到stdout是虚假的。如果禁用警告,stderr也将被忽略
蓝色

我知道我们可以忽略stderr,但是没有输出看起来有点奇怪...但是,如果可以接受,那么就可以接受。
乔纳森·艾伦

我个人不确定这是否可以接受,但是我可以说是对的吗?
蓝色


1

APL(Dyalog扩展)36 29 字节SBCS

这个答案归功于Extended的monad返回数字的素数,这比Dyalog Unicode中的基数转换更好。

编辑:-7字节感谢dzaima。

{2>⍵:0⋄(⊃=+/-⊃×2<≢)+⌿10⊤⍵,⍭⍵}

在线尝试!

说明

{1⋄(3)2}  A dfn, a function in brackets.  is a statement separator.
          The numbers signify the sections in the order they are explained.

2>⍵:0  If we have a number less than 2,
       we immediately return 0 to avoid a DOMAIN ERROR.

+⌿10⊤⍵,⍭⍵
        ⍭⍵  We take the factors of ⍵, our input as our right argument,
      ⍵,    and append it to our input again.
   10      before converting the input and its factors into a matrix of their base-10 digits
            (each row is the places, units, tens, hundreds, etc.)
+⌿         And taking their sum across the columns of the resulting matrix,
            to give us the sum of their digits, their digit-sums.

(⊃=+/-⊃×2<≢)  We run this section over the list of sums of digits above.
 ⊃=+/-⊃       We check if the main digit-sum (of our input)
               Is equal to the sum of our digit-sums
               (minus our main digit-sum that is also still in the list)
        ×2<≢   The trick here is that we can sneak in our composite check
               (if our input is prime there will be only two numbers, 
               the digit-sum of the prime,
               and the digit-sum of its sole prime factor, itself)
               So if we have a prime, we zero our (minus our main sum)
               in the calculation above, so that primes will not succeed in the check.
               We return the result of the check.

29个字节-{2>⍵:0⋄(⊃=+/-⊃×2<≢)+⌿10⊤⍵,⍭⍵}
dzaima


1

C(gcc)139136字节

S(m,i,t,h,_){t=m=m<2?2:m;for(_=h=i=1;m>1;h=1){while(m%++h);for(m/=h;i+=h%10,h/=10;);}while(t%++h);for(m=t;_+=m%10,m/=10;);m=t-h?i==_:0;}

在线尝试!

-3个字节,感谢ceilingcat

说明:

/* 
 * Variable mappings:
 *  is_smith      => S
 *  argument      => m
 *  factor_digits => i
 *  arg_copy      => t
 *  least_factor  => h
 *  digit_sum     => _    
 */
int is_smith(int argument){                     /* S(m,i,t,h,_){ */
    int factor_digits;
    int arg_copy;
    int least_factor;
    int digit_sum;

    /* 
     * The cases of 0 and 1 are degenerate. 
     * Mapping them to a non-degenerate case with the right result.
     */
    if (argument < 2) {                         /* t=m=m<2?2:m; */
        argument = 2;
    }
    arg_copy = argument;

    /* 
     * Initializing these to 1 instead of zero is done for golf reasons.
     * In the end we just compare them, so it doesn't really matter.
     */
    factor_digits = 1;                          /* for(_=h=i=1; */
    digit_sum = 1;

    /* Loop over each prime factor of argument */
    while (argument > 1) {                      /* m>1; */

        /*
         * Find the smallest factor 
         * Note that it is initialized to 1 in the golfed version since prefix
         * increment is used in the modulus operation.
         */
        least_factor = 2;                       /* h=1){ */
        while (argument % least_factor != 0)    /* while(m% */
            least_factor++;                     /* ++h); */
        argument /= least_factor;               /* for(m/=h; */

        /* Add its digit sum to factor_digits */
        while (least_factor > 0) {
            factor_digits += least_factor % 10; /* i+=h%10, */
            least_factor /= 10;                 /* h/=10;) */
        }                                       /* ; */

    }                                           /* } */

    /* In the golfed version we get this for free in the for loop. */
    least_factor = 2;
    while (arg_copy % least_factor != 0)        /* while(t% */
        least_factor++;                         /* ++h); */

    /* Restore the argument */
    argument = arg_copy;                        /* for(m=t; */

    /* Compute the arguments digit sum */
    while (argument > 0) {
        digit_sum += argument % 10;             /* _+=m%10, */
        argument /= 10;                         /* m/=10;) */
    }                                           /* ; */

    /* This return is done by assigning to first argument when golfed. */
                                                /* m= */
    if (arg_copy == least_factor) {             /* t==h? */
        return 0; /* prime input */             /* 0 */
    } else {                                    /* : */
        return digit_sum == factor_digits;      /* i == _ */
    }                                           /* ; */
}                                               /* } */

那引入了一些错误(例如2和3),但我认为仍然应该可以实现。
LambdaBeta

建议t-h&&i==_而不是t-h?i==_:0
ceilingcat

0

球拍176字节

(define(sd x)(if(= x 0)0(+(modulo x 10)(sd(/(- x(modulo x 10))10)))))
(require math)(define(f N)
(if(=(for/sum((i(factorize N)))(*(sd(list-ref i 0))(list-ref i 1)))(sd N))1 0))

如果为true,则返回1;如果为false,则返回0:

(f 27)
1
(f 28)
0
(f 85)
1
(f 86)
0

详细版本:

(define (sd x)   ; fn to find sum of digits
  (if (= x 0)
      0
      (+ (modulo x 10)
         (sd (/ (- x (modulo x 10)) 10)))))

(require math)
(define (f N)
  (if (= (for/sum ((i (factorize N)))
           (* (sd (list-ref i 0))
              (list-ref i 1)))
         (sd N)) 1 0))

0

锈-143字节

fn t(mut n:u32)->bool{let s=|k:u32| (2..=k).fold((0,k),|(a,m),_|(a+m%10,m/10));s(n).0==(2..n).fold(0,|mut a,d|{while n%d<1{n/=d;a+=s(d).0};a})}

@levitatinglion借来的python解决方案...至少这比Java短...

在play.rust-lang.org上删除


0

APL(NARS),33个字符,66个字节

{1≥≢k←π⍵:0⋄s←{+/⍎¨⍕⍵}⋄(s⍵)=+/s¨k}

“π⍵”返回列表因子⍵,假设输入为> = 1的一个正整数;测试:

  h←{1≥≢k←π⍵:0⋄s←{+/⍎¨⍕⍵}⋄(s⍵)=+/s¨k}
  (h¨1..100)/1..100
4 22 27 58 85 94 

0

C(gcc),177字节

定义一个函数Q,该函数对于史密斯编号返回0,对于非史密斯编号返回非零

#define r return
O(D,i){for(i=0;D>0;i+=D%10,D-=D%10,D/=10);r i;}D(O,o){for(o=1;o<O;)if(O%++o<1)r o;r O;}Q(p,q,i,j){if(p^(q=D(i=p))){for(j=0;p>1;q=D(p/=q))j+=O(q);r j^O(i);}r 1;}

在线尝试!

说明:

// Return the sum of digits of D if D > 0, otherwise 0
O(D,i){
    // While D is greater than 0:
    // Add the last digit of D to i, and remove the last digit from D
    for(i=0;D>0;i+=D%10,D-=D%10,D/=10);
    return i;
}
// Return the smallest prime factor of O if O>1 else O
D(O,o){
    // Iterate over numbers less than O
    for(o=1;o<O;)
        // If O is divisible by o return o
        if(O%++o<1)
            return o;
    // Otherwise return O
    return O;
}
Q(p,q,i,j){
    // Set q to D(p) and i to p
    // If p != D(p) (i.e, p is composite and > 0)
    if(p^(q=D(i=p))){
        // Iterate over the prime factors of p and store their digit sum in j
        for(j=0;p>1;q=D(p/=q))
            j+=O(q);
        // i is the original value of p. If O(i)^j == 0, O(i) == j
        return j^O(i);
    }
    // If p was composite or < 0, return 1
    return 1;
}


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.