0
\$\begingroup\$

This question already has an answer here:

The UPC Code consists of a bar code and a 12 digit number to identify the product. The first eleven digits are used to tell what product it is, and the last one is for error-checking purposes.

A UPC Code is valid if the sum

3 * d1 + 1 * d2 + 3 * d3 + 1 * d4 + ... + 1 * d12 = 0

Where dn is digit n of the code.

Challenge

Write a program which takes in a UPC code and does one of two things

  • If the UPC Code is not 12 digits, ask for input again.
  • If the UPC Code is 12 digits but invalid, ask for input again.
  • If the UPC Code is 12 digits and valid, terminate.

This is code-golf, so lowest number of bytes wins.

\$\endgroup\$

marked as duplicate by xnor code-golf Oct 25 '16 at 1:47

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • \$\begingroup\$ This is basically the same as the Luhn error-checking algorithm, so I'm closing this as a duplicate of that challenge. \$\endgroup\$ – xnor Oct 25 '16 at 1:47
  • \$\begingroup\$ Also, it should be noted that the formula isn't exactly right as shown. A valid sum should be divisible by ten (sum≡0(mod 10)), not equal to zero. \$\endgroup\$ – Geobits Oct 25 '16 at 2:07

Browse other questions tagged or ask your own question.