Generate numbers that add up to X

471 Views Asked by At

I have isolated the algorithm of a keygenme, but I am running into difficulty with creating the keygen.

The key has a length of seven digits, and the sum of each of the digits in the key must be divisible by seven and leave no remainder.

For example, the key 54135111 is valid since 5+4+1+3+5+1+1+1=21, and 21 is divisible by 7 with 0 remainder.

The way I am currently implementing the keygen is as follows:

1. Generate a seven-digit random number.
2. Check if that number is valid.
3. If it valid, display it to the user; if it is not valid, start over.

Is there a way in which I can more efficiently generate valid keys without having to inefficiently generate random numbers? I am using VB.NET/C#.

3

There are 3 best solutions below

0
On

x = any 6-digit number... 7-digit number = 10*x + mod(x, 7) ... Not mod(), but mod(sum()) ... you get the idea.

0
On

I improved on user4362's answer with this algorithm.

Public Function GenerateKey(ByVal sixDigitInt As String) As String
    Dim key as String = ""
    key = (10* sixDigitInt) + (7 - (DigitsSum(sixDigitInt) Mod 7))
    Return key
End Function
0
On

You can generate a six digit number. Denote its digit sum reminder when divided by $7$ by $d$, then taking the last digit to be $7-d$ would give you a seven digit number with the sum of the digits divisible by $7$.

Note: we can take the digit we added and place it anywhere in the $6$ digits we have, since the sum will remain the same