C[Sharp] Array Checksum

Back to General discussions forum

Miguel Munoz     2014-12-16 01:09:04

Hey guys, not sure what I am going wrong with this problem for Array Checksum

I manually type in the example problem, and I get the right answer. But every single random generator data I get wrong. I have no idea whats wrong. Maybe you guys can point it out?

// I edited the code to prevent spoiling solution,
// but to retain the crucial part (admin)

foreach (var i in inputData)
{
    result = (result + i)*seed;
    result = result%limit;
}
smwentum     2014-12-16 16:16:51

Hey Miguel,

This tripped me up too but your result can't be stored in an int. There is interger overflow(result will become too big and then turn negative) which will mess up your answer. Try long.

http://en.wikipedia.org/wiki/Integer_overflow

Rodion (admin)     2014-12-17 06:01:54
User avatar

Hello Miguel! Thanks for your question!

And thanks to smwentum for the answer!

Yes, it is really about overflow (which is mentioned in problem statement), but I think it is still possible to calculate even with int-s.

You only need to apply modulo twice - after adding next value, and then after multiplying. Result will be the same (see "modular arithmetics" task), but there will be no overflow, I hope.

Please login and solve 5 problems to be able to post at forum