tags:

views:

227

answers:

2

Does someone know how to solve this C# Math Algorithm?

The control number calculates by multiplying each number in a "social security number" with changing 2 and 1 (starting with 2). Then it calculates and adds together.

The control number should be equal divided with 10 to be correct and pass.

Ex, 720310-1212 "Social security number"

7* 2 = 14  --> 1+4

2* 1 = 2   --> 2 

0* 2 = 0   --> 0

3* 1 = 3   --> 3

1* 2 = 2   --> 2

0* 1 = 0   --> 0

1* 2 = 2   --> 2

2* 1 = 2   --> 2

1* 2 = 1   --> 2

2* 1 = 2   --> 2

Then add them 1+4+2+0+3+2+0+2+2+2+2 = 20

20/10 = 2 Pass!

+10  A: 

You need:

  • a counter to accumulate the numbers,
  • a loop to iterate over the input string,
  • char.GetNumericValue to get the numeric value of each input character,
  • a boolean flag that is changed each iteration to indicate whether to multiply by 1 or 2,
  • the modulus operator % to calculate the remainder of the division by 10 at the end.

Should be simple enough. Homework?


Edit

LINQ solution:

var valid = "720310-1212"
    .Where(c => char.IsDigit(c))
    .Select(c => (int)char.GetNumericValue(c))
    .Select((x, i) => x * (2 - i % 2))
    .Select(x => x % 10 + x / 10)
    .Sum() % 10 == 0;
dtb
+1 for Homework?
astander
LOL! Looks like homework to me.
Rap
It may be homework, but not necessarily; the given sample data looks like the Swedish counterpart of a social security number, and they are quite frequently used by various authorities and organizations as a sort of "customer number", so it's a rather common case that you wish to validate them (which is done according to the described algorithm). There does seem to be a student-ish age reference in the OP's nick name though...
Fredrik Mörk
Okay. In case it's not homework I added a LINQ solution. No lecturer will give any points for this solution if it doesn't come with two pages of documentation :-)
dtb
+2  A: 

I think you're describing the Luhn algorithm (also known as mod 10). It's used to validate credit cards (and other things). There is a C# implementation at E-Commerce Tip: Programmatically Validate Credit Card Numbers.

JP Alioto