0

I am running below function to do a sumcheck (Luhn's Alrgorithm) on any given card numbers but the check fails on some of the card numbers and also throws up runtime error: "Index out of bounds for type 'int[count]'." I guess this is something about the array being odd/even but unable to figure it out.

Have already tried running the loops to various counts like count+1 and count-1 etc.

int sum1 = 0;
int sum2 = 0;    
int count = digit_counter(cc_num);
int hold[count];

for(int i=0; i<count; i++)
{
   hold[i]= cc_num%10;
   cc_num = cc_num/10;  
}

for(int i=0; i<count; i++)
{
    printf("%i\n",hold[i]);    
}    

int i,j;
for (i=1,j=0; i<=count || j<count; i+=2,j+=2)
{
    hold[i] = hold[i]*2;
    if (hold[i]>10)
    {
        sum1+= (hold[i]/10)+(hold[i]%10);
    }
    else
    {
        sum1+= hold[i];
    }  
    sum2+=hold[j];

}
return sum1+sum2;

Should not throw up any runtime errors and be able to perform the sumcheck on all cards.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Rakesh Singh
  • 67
  • 1
  • 5
  • 1
    arrays are indexed zero-based (meaning the first element is index 0 and the last is count-1). So your loop condition `i<=count || j < count` is definitly wrong and should rather be `i < count && j < count`. I don't know the algorithm so I don't know if `i` should start at 0, too. – René Vogt Aug 31 '19 at 14:35

2 Answers2

1

As noted before, your loop has the wrong stop condition. Assuming that your cc_num holds pan without Luhn and your digit_counter works right you can try maybe something like:

int i;
for (i=0; i<count; ++i)
{
    bool isDouble=(count - i) % 2 != 0;
    sum1 += isDouble ? 2 * hold[i] % 10 + 2 * hold[i] / 10 : hold[i];
}
return 9 * sum1 % 10;
Michal Gluchowski
  • 1,197
  • 8
  • 16
-1

Try this one

int sum = 0;
bool odd = true;
for (int i = data.Length - 1; i >= 0; i--)
{
    if (odd == true)
    {
        int tSum = Convert.ToInt32(data[i].ToString()) * 2;
        if (tSum >= 10)
        {
            string tData = tSum.ToString();
            tSum = Convert.ToInt32(tData[0].ToString()) + Convert.ToInt32(tData[1].ToString());
        }
        sum += tSum;
    }
    else
        sum += Convert.ToInt32(data[i].ToString());
    odd = !odd;
}
return (((sum / 10) + 1) * 10) - sum;
René Vogt
  • 43,056
  • 14
  • 77
  • 99
Prophet Lamb
  • 530
  • 3
  • 17
  • The code posted by OP was in c, not c#. I guess they only tagged wrong (thatswhy I changed the tag already). – René Vogt Aug 31 '19 at 14:37