¿Es este un número de Smith?


28

Descripción del desafío

Un número de Smith es un número compuesto cuya suma de dígitos es igual a la suma de sumas de dígitos de sus factores primos. Dado un enteroN , determine si es un número de Smith o no.

Los primeros números son Smith 4, 22, 27, 58, 85, 94, 121, 166, 202, 265, 274, 319, 346, 355, 378, 382, 391, 438(secuencia A006753 en OEIS).

Entrada / salida de muestra

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

Notas

  • Su código puede ser una función (método) o un programa de trabajo completo,
  • En lugar de palabras como TrueyFalse , puede usar cualquier valor verdadero y falso, siempre que esté claro cuáles son,
  • Este es un desafío de , ¡así que haga su código lo más corto posible!

66
Tuve que leer esto: "la suma de dígitos es igual a la suma de sumas de dígitos de sus factores primos" varias veces: P
— Stewie Griffin

@StewieGriffin: Sí, es una oración bastante complicada, pero sentí que necesitaba dar una definición adecuada en lugar de confiar únicamente en los ejemplos :)
— shooqie

2
Esta es una de esas preguntas en las que pensé "Java + this = no", aunque voté por la idea: P
— Shaun Wild

3
A veces noto patrones en números, suma de dígitos, etc., pero realmente, ¿la gente nota cosas como esta: "Albert Wilansky acuñó el término número de Smith cuando notó la propiedad definitoria en el número de teléfono de su cuñado" ?
— Stewie Griffin

1
@StewieGriffin: Sí, es como Ramanujan y 1729, siempre me desconcertó también.
— shooqie

Respuestas:


9

Jalea , 12 11 bytes

Æfḟȯ.DFżDSE

Devuelve 1 para los números de Smith y 0 en caso contrario. Pruébalo en línea! o verificar todos los casos de prueba .

Fondo

Æf(factorización prima) y D(entero a decimal) se implementan de modo que P(producto) yḌ (decimal a entero) constituyan inversos izquierdos.

Para los enteros -4 a 4 , Æfdevuelve lo siguiente.

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

Para los números -10, -1, -0.5, 0, 0.5, 1, 10 , Ddevuelve lo siguiente.

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

Cómo funciona

Æ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
¡Esta es una solución realmente genial que tengo que decir!
— Emigna

@Emigna - Es lo que hice, pero lo implementé de una manera muy superior: D
— Jonathan Allan

@JonathanAllan Desafortunadamente no hablo jalea, así que no tengo idea de lo que hace tu código :)
— Emigna

1
@Emigna: sí, había planeado resolver cómo jugar golf antes de agregar una sección de cómo funciona.
— Jonathan Allan

9

Python 2, 122 115 110 106 bytes

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

Guardado 4 bytes gracias a Dennis

Pruébalo en ideone.com

Explicación

Lee un número en stdin y Truemuestra si el número es un número Smith o Falsesi no lo es.

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
Abajo votante - podría ser útil agregar un comentario para explicar por qué
— Jonathan Allan

66
@JonathanAllan El voto negativo fue emitido automáticamente por el usuario de la Comunidad cuando se editó la respuesta. Considero que esto es un error .
— Dennis

1
La última línea se puede reescribir como print n<m>s==sum(map(int,`m`)).
— Dennis

@ Dennis ¡Es un gran uso de la comparación encadenada!
— LevitatingLion

8

Brachylog , 19 bytes

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

Pruébalo en línea!

Explicación

@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 Sí . En Brachylog, el signo negativo para los números es _(llamado bajo menos ).
— Fatalize

7

05AB1E , 11 17 bytes

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

Explicación

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

Pruébalo en línea!


5

PowerShell v3 +, 183 bytes

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)

No hay verificación principal incorporada. Sin factorización incorporada. Sin suma de dígitos incorporada. Todo está hecho a mano. :RE

Toma la entrada $ncomo un entero, establece $bigual a una matriz vacía. Aquí $bestá nuestra colección de factores primos.

El siguiente es un forbucle. Primero establecemos $aigual a nuestro número de entrada, y el condicional es hasta que $asea ​​menor o igual que 1. Este ciclo va a encontrar nuestros factores primos.

Realizamos un ciclo de 2hasta $a, utiliza Where-Object( |?{...}) para extraer primos que también son factores !($a%$_). Esos se alimentan en un bucle interno |%{...}que coloca el factor $by lo divide $a(por lo tanto, finalmente lo haremos 1).

Entonces, ahora tenemos todos nuestros factores primos $b. Es hora de formular nuestra salida booleana. Tenemos que verificar que $nes -notin $b, porque si es que eso significa que $nes primo, y por lo tanto no es un número Smith. Además, ( -and) debemos asegurarnos de que nuestros dos conjuntos de sumas de dígitos sean -equal. El booleano resultante se deja en la tubería y la salida es implícita.

NB : requiere v3 o más reciente para el -notinoperador. Todavía estoy ejecutando la entrada para 4937775(esto es lento de calcular), así que actualizaré esto cuando termine. Después de más de 3 horas, recibí un error de stackoverflow. Entonces, hay un límite superior en alguna parte. Oh bien.

Esto funcionará para una entrada negativa, cero o uno, porque la mano derecha de la -andbarra emitirá un error mientras intenta calcular las sumas de dígitos (que se muestran a continuación), lo que hará que esa mitad vaya a $falsecuando se evalúa. Dado que STDERR se ignora por defecto , y la salida correcta todavía se muestra, esto está bien.


Casos de prueba

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

Jalea , 27 25 23 bytes

(golf más probable que definitivamente es posible)

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

Devoluciones 0para falso o 1verdadero

Todos los casos de prueba en TryItOnline

¿Cómo?

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

En realidad, 18 bytes

Desafortunadamente, en realidad no tiene una factorización incorporada que proporcione los factores primos de un número a la multiplicidad, por lo que tuve que hackear uno juntos. Sugerencias de golf bienvenidas. Pruébalo en línea!

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

No golfista

         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 bytes

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

Octava, 80 78 bytes

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

Explicación:

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

Pruébalo en línea .


1
Eso any(t<0)de no primalidad es muy inteligente
— Luis Mendo

2

Pyth, 21 bytes

&&>Q1!P_QqsjQTssmjdTP

Un programa que toma la entrada de un entero e imprime Trueo Falsesegún sea relevante.

Pruébalo en línea

Cómo funciona

&&>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 bytes

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

Una función anónima que devuelve un Bool.

  • Ahora realiza la factorización manual al 100% y la comprobación de primalidad.
  • Se guardaron algunos bytes al probar "entrada> 1" y "número de factores> 1" con una comparación encadenada, ya que m> Ω (m) .

( pruébalo en línea )

EDITAR: -1 byte gracias a b2gills


2..i-1se deletrea mejor como 2..^i.
— Brad Gilbert b2gills

2

Java 7, 509 506 435 426 419 230 bytes

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

Debería haber escuchado el comentario de @BasicallyAlanTuring .

Esta es una de esas preguntas donde pensé "Java + this = no", aunque voté por la idea: P

Ah, bueno ... Algunos lenguajes de programación usan un solo byte para los factores primos o la verificación principal, pero Java ciertamente no es uno de ellos.

EDITAR: Redujo a la mitad la cantidad de bytes ahora que tuve algo de tiempo para pensarlo.

Ungolfed (sort-off ..) y casos de prueba:

Pruébalo aquí

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

Salida:

false
true
false
true
false
false
false
true

2

Brachylog (más nuevo) , 11 bytes

¬ṗ&ẹ+.&ḋcẹ+

Pruébalo en línea!

El predicado tiene éxito si la entrada es un número de Smith y falla si no lo es.

               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.



1

Pyke, 16 bytes

Pm[`mbs(sQ[qRlt*

Pruébalo aquí!


1
Errores sin resultado para entrada menor que2
— Jonathan Allan

@JonathanAllan ninguna salida a stdout es falsa Si las advertencias están deshabilitadas, stderr también se ignora
— Azul

Sabía que podemos ignorar stderr, pero ninguna salida parece un poco extraña ... pero si es aceptable, entonces es aceptable.
— Jonathan Allan

Personalmente, no estoy seguro de si es aceptable, pero puedo decir que es correcto.
— Azul

1

Perl 6 , 80 bytes

{.[0]==.flat.skip.sum}o($!={.comb.sum,($/=first $_%%*,2..^$_)&&map $!,$/,$_/$/})

Pruébalo en línea!

Bloque de código anónimo que toma un entero y devuelve un booleano.


1

APL (Dyalog Extended) , 36 29 bytes SBCS

Esta respuesta le debe su golfidad a la ⍭mónada de Extended por devolver los factores primos de un número, y eso ⊤es mejor en la conversión de base que en Dyalog Unicode.

Editar: -7 bytes gracias a dzaima.

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

Pruébalo en línea!

Explicación

{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 bytes -{2>⍵:0⋄(⊃=+/-⊃×2<≢)+⌿10⊤⍵,⍭⍵}
— dzaima


1

C (gcc) , 139 136 bytes

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

Pruébalo en línea!

-3 bytes gracias a ceilingcat

Explicación:

/* 
 * 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 == _ */
    }                                           /* ; */
}                                               /* } */

Eso introdujo algunos errores (por ejemplo, 2 y 3), pero creo que aún debería ser posible.
— LambdaBeta

Sugerir en t-h&&i==_lugar det-h?i==_:0
— ceilingcat

0

Raqueta 176 bytes

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

Devuelve 1 si es verdadero y 0 si es falso:

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

Versión detallada:

(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

Óxido - 143 bytes

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

solución de python prestada por @levitatinglion ... al menos esto es más corto que Java ...

degolfed en play.rust-lang.org


0

APL (NARS), 33 caracteres, 66 bytes

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

Factores de la lista de retorno "π⍵" de ⍵, suponga que la entrada es un entero positivo> = 1; prueba:

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

0

C (gcc), 177 bytes

Define una función Qque devuelve 0 para números smith y no cero para números no smith

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

Pruébalo en línea!

Explicación:

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


Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.