I am working on a Visa credit card generator and I'm not seeing the problem with the following:
My code seems to work for 16 digit card numbers, however, it doesn't seem to work for 13 digit cards, as the generated card numbers are invalid on both online testers and on my app.
Code:
var randomNum = new Random();
int [] lengths = new int[] { 13, 16 };
int length = lengths[randomNum.Next(lengths.Length)];
int [] str;
int [] reversed;
var lastDigit = 0;
var sum = 0;
if (length == 16)
{
str = new int[16];
reversed = new int[15];
}
else
{
str = new int[13];
reversed = new int[12];
}
Random rnd = new Random();
while (pos < length - 1)
{
str[pos++] = rnd.Next(0, 9);
}
for (int i = 0; i < str.Length - 1; i++)
{
reversed[i] = str[str.Length - i - 2];
}
for (pos = 0; pos < length - 1; pos++)
{
if (pos % 2 == 0 && length == 16)
{
reversed[pos] *= 2;
if (reversed[pos] > 9)
reversed[pos] = reversed[pos] - 9;
}
else if (pos % 2 == 1 && length == 13)
{
reversed[pos] *= 2;
if (reversed[pos] > 9)
reversed[pos] = reversed[pos] - 9;
}
sum += reversed[pos];
}
lastDigit = (10 - (sum % 10)) % 10;
str[length - 1] = lastDigit;
I apologize for copying the whole code, but I thought it would make things more understandable.
The algorithm I followed from http://www.freeformatter.com/credit-card-number-generator-validator.html:
Drop the last digit from the number. The last digit is what we want to check against
Reverse the numbers
Multiply the digits in odd positions (1, 3, 5, etc.) by 2 and
subtract 9 to all any result higher than 9
Add all the
numbers together
The check digit (the last number of the card) is the amount that you
would need to add to get a multiple of 10 (Modulo 10)
Sample card numbers generated by my code:
16 digit: 4145422641287432 - Valid
13 digit: 4354735186403 - Invalid
(The sum before adding the check
digit was 47 meaning 3 would be the check digit resulting in the whole sum being 50 => 50%10=0)
What exactly am I doing wrong here?
Related
This question already has answers here:
Linq query to get all numbers (positive and negative) up to N that sum up to number K
(5 answers)
Listing all permutations of a string/integer
(28 answers)
Closed 1 year ago.
Given input: N = 6, X = 3
The output should be:
1 + 2 + 3 - 4 - 5 + 6 = 3
1 + 2 - 3 + 4 + 5 - 6 = 3
1 - 2 - 3 - 4 + 5 + 6 = 3
So far I could manage this:
//returns a string of numbers from 1 to N
static string Numbers(int maxNumber) => maxNumber > 1 ? Numbers(maxNumber - One) + maxNumber :"1";
and a function that generates all possible combinations for +- but the problem is that I want to combine the +- resulted string with numbers from 1 to N:
static void Permute(char[] arry, int i, int n)
{
int j;
if (i == n)
Console.WriteLine(arry);
else
{
for (j = i; j <= n; j++)
{
Swap(ref arry[i], ref arry[j]);
Permute(arry, i + 1, n);
Swap(ref arry[i], ref arry[j]); //backtrack
}
}
}
static void Swap(ref char a, ref char b)
{
char tmp;
tmp = a;
a = b;
b = tmp;
}
This looks like a very different form of "permute". For N integers, you have D=N-1 decisions to make, each of which can be either a + or a -. Two options is: "binary", so, if this is me, I would compute (2^D)-1 (which gives us the upper bound), then do a for loop from zero to that number (inclusive), and do the math: each binary digit is a decision point, and we could say 0===- and 1===+; see what the result is: if it is the number you wanted: log it.
For N=6 we have D=5, and 32 attempts to do; 0 thru 31:
int N = 6, X = 3;
// how many decisions is that?
var decisions = N - 1;
// treat each -/+ as one of "decisions" binary digits
var binaryUpperLimit = (1 << decisions) - 1;
for (int i = 0; i <= binaryUpperLimit; i++)
{
// compute the sum
int sum = 1; // the 1 is a permenant fixture, it seems
// determine each decision using binary arithmetic
for (int place = 0; place < decisions; place++)
{
int digit = place + 2;
if ((i & (1 << place)) == 0)
{
sum -= digit;
}
else
{
sum += digit;
}
}
// is that what we wanted?
if (sum == X)
{
// we have a "hit"; repeat the above to output this
Console.Write("1");
for (int place = 0; place < decisions; place++)
{
if ((i & (1 << place)) == 0)
{
Console.Write(" - ");
}
else
{
Console.Write(" + ");
}
int digit = place + 2;
Console.Write(digit);
}
Console.Write(" = ");
Console.WriteLine(sum);
}
}
(if the initial 1 can be negative, you'll need to adjust to add an extra decision, start the sum at zero, and make digit be +1 instead of +2)
I was able to get my array to sort to the right but, struggling
to get the left rotation to work for example [1, 2, 3, 4, 5, 6, 7, 8] if
rotated to the left 4 spaces [4, 5, 6, 7, 8, 1, 2, 3] I feel like it's super simple and just a small change to my current right rotation but, I'm stumped.
if (direction == "right")
{
{
//make spaces<nums.Length
if (spaces > newArray.Length)
{
while (spaces - newArray.Length >= 0)
{
spaces = spaces - newArray.Length;
}
}
if (spaces == 0)
{
}
else
{
int[] temp = new int[spaces];
//move to a temp array
for (var i = temp.Length - 1; i >= 0; i--)
{
temp[i] = newArray[newArray.Length - spaces + i];
}
//push to the end
for (var j = newArray.Length - spaces - 1; j >= 0; j- -)
{
newArray[j + spaces] = newArray[j];
}
//put the ones in temp array back to the top
for (var s = 0; s < temp.Length; s++)
{
newArray[s] = temp[s];
}
}
}
}
Wel, if you want it simple, try Linq and modulo arithmetics:
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
int shift = 4;
int[] result = Enumerable
.Range(0, array.Length)
.Select(i => array[(i + shift % array.Length + array.Length) % array.Length])
.ToArray();
Same modulo arithmetics and no Linq
int shift = 4;
int[] result = new int[array.Length];
for (int i = 0; i < result.Length; ++i)
result[i] = array[(i + shift % array.Length + array.Length) % array.Length];
If you want to rotate to right, assign negative values to shift.
Edit: what's going under the hood, modulo arithmetics explained. Our task is when we are given i (index of result) to compute index of the initial array:
array = {1 2 3 4 5 6 7 8}
result = {5 6 7 8 1 2 3 4}
as we can see,
index = i + shift
when shift is small enough (5 is taken from 0 + 4 == 4th index). However we can't exceed arrays length but should subtract it (i.e. restart from 0)
7 + 4 == 11 -> 11 - 8 == 3
I.e.
index = i + shift
index >= array.Length
? index - array.Length // index is too large, restart from 0
: index; // index is small enough
This operation is equal to remainder %:
index = (i + shift) % array.Length
It's good enough, but we still have 2 specific issues with .Net:
i + shift can result in integer oveflow (when, say shift = int.MaxValue)
.Net can well return negative remainder (if shift < 0)
That's why shift % array.Length to meet the first issue and + array.Length for the second. Finally
(i + shift % array.Length + array.Length) % array.Length
Write a program that fills a 15-byte array with positive double-digit random numbers. in each number, the sum of the two digits is equal to 9.
Here's what I've done so far:
int one = 0;
int two = 0;
int[] arr = new int[15];
Random rnd = new Random();
for (int i = 0; i < arr.Length; i++)
{
arr[i] = rnd.Next(10, 99);
one = arr[0] % 10;
two = arr[0] / 10;
if (arr[i] % 2 == 0 && one + two == 9)
Console.WriteLine(arr[i]);
}
The problem with your solution is that rnd.Next(10, 99) will not always produce number with the properties that you want. you should write a code that always works.
We know that sum of digits of a number should be 9. if we assume our two-digit number to be a*10+b where a and b are digits and a + b = 9, we can randomly generate a from 1 to 9.
Then we can calculate other digit b = 9 - a.
therefor our final result would be a*10 + 9 - a which will be simplified to a*9 + 9 where a is random number from 1 to 9, here are two examples.
a=7 then 7 * 9 + 9 = 72, 7 + 2 = 9
a=3 then 3 * 9 + 9 = 36, 3 + 6 = 9
note that a is in this range 1 <= a < 9
I want to find the total number of digits divisible by 5 between 1 - 100, in C# windows form, how to proceed from here?
int sum;
private void button2_Click(object sender, EventArgs e)
{
int[] intarray = new int[100];
for (int i = 0; i < 99; i++)
{
intarray[i] = i + 1;
}
foreach (int a in intarray)
{
if (a / 5 == 0)
{
}
}
}
Note than a / 5 == 0 is wrong. For example 10 is divisible by 2, the result is 10/5 = 2, not equal to 0.
if (a % 5 == 0)
{
//then a is divisible by 5. print or store it
}
The modulus operator, also known as Remainder, returns the remainder of the integer division.
Therefore, the full answer:
int nInRange = 0;
foreach (int a in intarray)
if (a % 5 == 0)
nInRange++;
Maybe this is what you want.
public static IEnumerable<int> GetIntsDivisible(int start, int finish, int divisor)
{
for (var i = start; i <= finish; i++)
if (i % divisor == 0)
yield return i;
}
public static void Main()
{
Console.WriteLine(string.Join(", ", GetIntsDivisible(1, 100, 5)));
}
or if you don't want to yield
public static List<int> GetIntsDivisible(int start, int finish, int divisor)
{
var result = new List<int>();
for (var i = start; i <= finish; i++)
if (i % divisor == 0)
result.Add(i);
return result;
}
Output
5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100
Full demo here
Initialize a variable as 0
for e.g. Count = 0;
then add statement Count++ in your if block as follows:
if (a % 5 == 0)
{
Count++;
}
Since question is a bit vague in exact requirement, I will write the basic logic that can find the numbers exactly divisible by other number.
There is something called modulus (%) operator. It gives you the remainder of division.e.g. 11%5 will be 1, 13%5 will be 3, whereas 15%5 will be 0
so logic goes like,
for(int i=0;i<=100;i++)
{
if((i%5)==0)
{
\\this is ur number
}
}
Every one has address your question but no one talk about this weird attempt.
I really think you should take 5 minute and read your code because you are just running everywhere.
You should take the pen and paper before going head first into coding.
Here is a simple reading of your code so you understand what you were doing.
Line 1:
int[] intarray = new int[100];
So you start win an array, I guess it's for the result, right ? You will not be storing the number from 1 to 100 for no reason?
Line 2:
for (int i = 0; i < 99; i++)
Now we count from 0 to 98, I though it was form 1 to 100 .. Yes 98 as you are using < instead of <=
Line 3:
intarray[i] = i + 1;
Why ? 3rd line and you are already lost! You are filling the array with number you just iterate. It's like filling a bottle with water, then use it to fill an other bottle because you needed water.
If you iterate from 1 to 100 you could have check if it was divisible.
for (int i = 1; i <= 100; i++)
Line 4:
foreach (int a in intarray)
Again ? We are back counting from 1 to 100..
Line 5:
if (a / 5 == 0)
If this is suppose to tell you if it divisible thats wrong. The correct math operator is the Modulo. The division symbole won't give you the result you expect.
{1,2,3,4} will give you True. Anything else will be false.
int count = 0;
for (int i = 1; i <= 100; i++)
{
if ((i % 5) == 0)
{
count++;
textBox1.Text = count.ToString();
}
}
Alternatively,
int num = (100 + 5) / 5 - (1 + 5 - 1) / 5;
//Show result here
I'm working on a math game in the Unity game engine using C#, specifically a reusable component to teach the grid method for multiplication. For example, when given the numbers 34 and 13, it should generate a 3X3 grid (a header column and row for the multiplier and multiplicand place values and 2X2 for the number of places in the multiplier and multiplicand). Something that looks like this:
My issue is that I don't know the best way to extract the place values of the numbers (eg 34 -> 30 and 4). I was thinking of just converting it to a string, adding 0s to the higher place values based on its index, and converting it back to an int, but this seems like a bad solution. Is there a better way of doing this?
Note: I'll pretty much only be dealing with positive whole numbers, but the number of place values might vary.
Thanks to all who answered! Thought it might be helpful to post my Unity-specific solution that I constructed with all the replies:
List<int> GetPlaceValues(int num) {
List<int> placeValues = new List<int>();
while (num > 0) {
placeValues.Add(num % 10);
num /= 10;
}
for(int i = 0;i<placeValues.Count;i++) {
placeValues[i] *= (int)Mathf.Pow(10, i);
}
placeValues.Reverse();
return placeValues;
}
Take advantage of the way our number system works. Here's a basic example:
string test = "12034";
for (int i = 0; i < test.Length; ++i) {
int digit = test[test.Length - i - 1] - '0';
digit *= (int)Math.Pow(10, i);
Console.WriteLine("digit = " + digit);
}
Basically, it reads from the rightmost digit (assuming the input is an integer), and uses the convenient place value of the way our system works to calculate the meaning of the digit.
test.Length - i - 1 treats the rightmost as 0, and indexes positive to the left of there.
- '0' converts from the encoding value for '0' to an actual digit.
Play with the code
Perhaps you want something like this (ideone):
int n = 76302;
int mul = 1;
int cnt = 0;
int res[10];
while(n) {
res[cnt++] = (n % 10) * mul;
mul*=10;
cout << res[cnt-1] << " ";
n = n / 10;
}
output
2 0 300 6000 70000
My answer is incredibly crude, and could likely be improved by someone with better maths skills:
void Main()
{
GetMulGrid(34, 13).Dump();
}
int[,] GetMulGrid(int x, int y)
{
int[] GetPlaceValues(int num)
{
var numDigits = (int)Math.Floor(Math.Log10(num) + 1);
var digits = num.ToString().ToCharArray().Select(ch => Convert.ToInt32(ch.ToString())).ToArray();
var multiplied =
digits
.Select((d, i) =>
{
if (i != (numDigits - 1) && d == 0) d = 1;
return d * (int)Math.Pow(10, (numDigits - i) - 1);
})
.ToArray();
return multiplied;
}
var xComponents = GetPlaceValues(x);
var yComponents = GetPlaceValues(y);
var arr = new int[xComponents.Length + 1, yComponents.Length + 1];
for(var row = 0; row < yComponents.Length; row++)
{
for(var col = 0; col < xComponents.Length; col++)
{
arr[row + 1,col + 1] = xComponents[col] * yComponents[row];
if (row == 0)
{
arr[0, col + 1] = xComponents[col];
}
if (col == 0)
{
arr[row + 1, 0] = yComponents[row];
}
}
}
return arr;
}
For your example of 34 x 13 it produces:
And for 304 x 132 it produces:
It spits this out as an array, so how you consume and display the results will be up to you.
For two-digit numbers you can use modulo
int n = 34;
int x = n % 10; // 4
int y = n - x; // 30