Saída dos produtos parciais


17

Na multiplicação longa , depois de multiplicar os números, você fica com os produtos parciais; nesse desafio, você produzirá esses produtos parciais.

Como a multiplicação longa é longa, para compensar seu código precisará ser o mais curto possível.

Exemplos

34, 53
102, 1700

48, 38 
384, 1440

361, 674
1444, 25270, 216600

0, 0
0

1, 8
8

Especificações

  • Entrada / Saída pode estar em qualquer formato razoável, como matriz, sequência separada por vírgula (ou qualquer outro delimitador que não seja um dígito), lista, argumentos de função etc.
  • Os produtos parciais devem estar em ordem crescente.
  • Se um produto parcial for 0, você pode escolher se deseja produzi-lo ou não.

Este é o pelo que o código mais curto em bytes vence!


Estou assumindo que os números podem ser cadeias, certo?
Mama Fun Roll

Esse caso de teste 0,0 está tornando muito mais difícil.
Xnor

Qual é o resultado esperado 12, 102? A maioria das respostas parece retornar 24, 0, 1200.
Dennis

@Dennis 24, 0, 1200está bem. Vou especificar no post
Downgoat

Respostas:


4

Gelatina, 10 bytes

DU×µLR’⁵*×

Experimente online!

Como funciona

DU×µLR’⁵*×  Left argument: multiplier -- Right argument: multiplicant

D           Convert the multiplier to base 10 (array of digits).
 U          Reverse the array.
  ×         Multiply each digit by the multiplicant.
   µ        Begin a new, monadic chain. Argument: A(array of products)
    L       Get the length of A.
     R      Turn length l into [1, ..., l].
      ’     Decrement to yield [0, ..., l-1].
       ⁵*   Compute 10**i for each i in that range.
         ×  Hook; multiply the powers of ten by the corresponding elements of A.

3
Eu estou supondo que o nome dessa linguagem vem do fato de que todos fazem sentir geléia.
geokavel

7

Pitão, 12 bytes

.e**Qsb^Tk_w

Suíte de teste

Separa a nova linha de entrada, por exemplo

361
674

Explicação:

.e**Qsb^Tk_w
                Implicit: Q = eval(input()),T = 10
           w    Input the second number as a string.
          _     Reverse it.
.e              Enumerated map, where b is the character and k is the index.
     sb         Convert the character to an int.
   *Q           Multiply by Q.
  *    ^Tk      Multiply by T ^ k. (10 ^ index)

4

JavaScript (ES7), 48 bytes

(a,b)=>[...b+""].reverse().map((d,i)=>10**i*a*d)

ES6 (56 bytes)

(a,b)=>[...b+""].reverse().map((d,i)=>a*d+"0".repeat(i))

Explicação

Retorna uma matriz de produtos parciais como números.

(a,b)=>
  [...b+""]    // convert the multiplier to an array of digits
  .reverse()   // reverse the digits of the multiplier so the output is in the right order
  .map((d,i)=> // for each digit d of the multiplier
    10**i      // get the power of ten of the digit
      *a*d     // raise the product of the digit to it
  )

Teste

O teste é usado em Math.powvez de **fazê-lo funcionar em navegadores padrão.


3

Lua, 72 68 bytes

b=arg[2]:reverse()for i=1,#b do print(arg[1]*b:sub(i,i)*10^(i-1))end

3

APL, 21 bytes

{⍺×x×10*1-⍨⍳≢x←⊖⍎¨⍕⍵}

Esta é uma função diádica que aceita números inteiros à esquerda e à direita e retorna uma matriz. Para chamá-lo, atribua-o a uma variável.

Explicação:

             x←⊖⍎¨⍕⍵} ⍝ Define x to be the reversed digits of the right input
     10*1-⍨⍳≢         ⍝ Generate all 10^(1-i) for i from 1 to the number of digits
{⍺×x×                 ⍝ Multiply the right input by the digits and the powers of 10

11
⍎¨⍕é muito inteligente.
Dennis

2

05AB1E , 15 bytes

Código:

VDgUSXFTNmY**=\

Explicação:

VDgUSXFTNmY**=\

V                 # Assign the input to Y
 D                # Duplicate of input, because the stack is empty
  g               # Pushes the length of the last item
   U              # Assign the length to X
    S             # Split the last item
     X            # Pushes X (length of the last item)
      F           # Creates a for loop: for N in range(0, X)
       TNm        # Pushes 10 ^ N
          Y       # Pushes Y (first input)
           *      # Multiplies the last two items
            *     # Multiplies the last two items
             =    # Output the last item
              \   # Discard the last item

2

Pitão, 26 bytes

DcGHKjHTFNJlK*G*@Kt-JN^TN

Isso define uma função cque aceita 2argumentos e a função imprime os produtos parciais.

DcGHKjHTFNJlK*G*@Kt-JN^TN
DCGH                      Define function c(G, H)
    KjHT                  Set K to the list of digits converting H to base 10
        FNJlK             Set J to the length of K and loop with variable N
                          (Implicit: print)
             *G*@Kt-JN    Calculates the partial product
                      ^TN Raising it to the appropriate power of 10

1

MATL , 18 bytes

ij48-tn:1-P10w^**P

O compilador (5.1.0) funciona no Matlab e no Octave.

Cada número é inserido em uma linha separada.

Exemplo

>> matl ij48-tn:1-P10w^**P
> 361
> 674
1444  25270 216600

Explicação

i           % input first number (say 361)
j           % input second number, interpreted as a string (say '674')
48-         % subtract '0' to obtain vector of figures (gives [6 7 4])
tn:1-P      % vector [n-1, ... 1, 0] where n is the number of figures (gives [2 1 0])
10w^        % 10 raised to that, element-wise (gives [100 10 1])
*           % multiply, element-wise (gives [600 70 4])
*           % multiply (gives 361*[600 70 4], or [216600 25270 1444])
P           % flip vector ([1444 25270 216600]). Implicitly display

1

Haskell, 60 57 54 bytes

g x=zipWith(\b->(x*10^b*).read.pure)[0..].reverse.show

5 bytes a menos (solte .show) se eu puder pegar o segundo número como uma string.

Exemplo de uso: g 361 674-> [1444,25270,216600].

Multiplique cada dígito do reverso de ycom xe escala com 10^ionde i = 0,1,2,....

Edit: Obrigado a @Mauris por 3 bytes!


Você pode até fazer (\b->(x*10^b*).read.pure).
Lynn

@Mauris: Legal. Muito obrigado!
N30

1

Julia, 50 49 bytes

f(a,b)=[a*d*10^~-i for(i,d)=enumerate(digits(b))]

Esta é uma função que aceita dois números inteiros e retorna uma matriz inteira.

A digitsfunção retorna uma matriz dos dígitos do número inteiro de entrada na ordem inversa. Obtemos o índice, pares de valores usando enumeratee calculamos os produtos parciais como a primeira entrada vezes os dígitos vezes 10 aumentados para a potência do índice do dígito - 1.

Guardado um byte graças a Dennis!


1

Python 2, 61

def p(a,b):
 j=0
 while b>0:
  print`b%10*a`+j*'0';b/=10;j+=1 

1

CJam, 19 17 bytes

q~W%eef{~~A@#**}p

Recebe entrada com o primeiro item sendo um número inteiro e o segundo uma string (por exemplo 34 "53"). Sugestões são bem-vindas, pois tenho certeza de que pode ser mais curta. Agradecemos a Dennis por salvar dois bytes.

Experimente online.

Explicação

q~    e# Get input and evaluate it, x and "y"
W%    e# Reverse y so it will be properly sorted
ee    e# Enumerate through y with each character and its index
f{    e# For each digit in y...
  ~~  e# Convert the digit to an integer on the stack
  A@# e# Take 10 to the power of y's index
  **  e# Multiply all three together to get the final result
}
p     e# Print the array

11
~~A@#**salva alguns bytes.
Dennis

1

Haskell, 37 bytes

a%0=[]
a%b=b`mod`10*a:(a*10)%div b 10

Não rigoroso, apenas aritmético. Anexa recursivamente o menor produto parcial ao restante, onde o último dígito de bé truncado e um multiplicador de 10 é aplicado. A precedência do operador funciona bem.


0

, 11 caracteres / 23 bytes (não competitivo)

ᴙíⓢⓜî*$*Ⅹⁿ_

Try it here (Firefox only).

Encontrou um erro ao codificar a solução para este problema ...

Explicação

          // Implicit: î = input 1, í = input 2
ᴙíⓢ      // reverse í and split it into an array
ⓜî*$*Ⅹⁿ_ // multiply î by each individual digit in í and put in previous array
          // implicit output

0

Japonês , 28 bytes

I=[]Vs w m@IpApY+1 /A*U*X};I

Explicação:

I=[]Vs w m@IpApY+1 /A*U*X};I
I=[]                         //that's simple, init an array I
    Vs                       //take the second input and convert to string
       w                     //reverse it and...
         m@              }   //...map through the chars; X is a char, Y is counter
           Ip............    //push the following value into I...
             ApY+1 /A*U*X    //10^(Y+1)/10*U*X, U is the first input
                           I //output the resulting array

Devido ao erro no intérprete, é necessário usar ApY+1 /10 vez de ApY, porque Ap0(que é 10 ^ 0) dá 100. Acho que é pelo motivo de permitir o esquadrinhamento rápido Ap, mas 0não significa "sem argumentos". Plz fix, Eth.
Nicael 30/12/2015

0

Python 2, 42 bytes

f=lambda a,b:b*[0]and[b%10*a]+f(a*10,b/10)

Não rigoroso, apenas aritmético. Anexa recursivamente o menor produto parcial ao restante, onde o último dígito de bé truncado e um multiplicador de 10 é aplicado.

Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.