+ 1

trailing zeros only works up to number 12

the following code works but only up to the number 12 after that the factorials are calculated wrong any help on how to fix this would be much appreciated thank you //only works for numbers less than 12 for some reason Console.WriteLine(""); Console.Write("Enter a number : "); string Num = Console.ReadLine(); int NUM; while(!int.TryParse(Num,out NUM) | NUM < 1 | NUM >12) { Console.WriteLine("You must enter a number greater than 0 and less than 13 : "); Num = Console.ReadLine(); } int fact=1; for (int a = NUM; a > 1; a--) { fact = fact * a; } string Fact = fact.ToString(); int x = Fact.Length; int y = 0; for (int a = x-1; a >=0; a--) { if (Fact[a].ToString().Contains("0")) { y = y + 1; } else { break; } } Console.WriteLine("{0}! is {1} and ends in {2} zeros",Num,Fact,y);

3rd Oct 2018, 10:00 PM
David Aseltine
David Aseltine - avatar
10 Respuestas
+ 6
David Aseltine The upper bound for int is just merely 2,147,483,647 and that's 31 ones in binary for a 32-bit data type. Yes double (64-bit) would works too but the appropriate data type is ulong for storing factorial as it's unsigned (always positive) that allows to store more numbers at 128-bits. 😉 📖 Further reading 📖 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ulong
3rd Oct 2018, 11:07 PM
Zephyr Koo
Zephyr Koo - avatar
+ 4
David Aseltine You're welcome! 😄 Anyway for your info you may use the @ symbol to tag person in the discussion to notify the user. 👍
4th Oct 2018, 4:10 AM
Zephyr Koo
Zephyr Koo - avatar
+ 1
Zephyr Koo thank you I didn't realize how different each type of variable actually was
3rd Oct 2018, 11:12 PM
David Aseltine
David Aseltine - avatar
+ 1
ODLNT unfortunately that link did not work but I will do some research on the topic and see what I can find thank you for letting me know there is another (easier?) way to do this problem
3rd Oct 2018, 11:14 PM
David Aseltine
David Aseltine - avatar
0
I'm not fluent in C#, but is the method 'contains' the right choice? You want to count only the zeros at the end, not those in the middle ...
3rd Oct 2018, 10:14 PM
HonFu
HonFu - avatar
0
it's only looking at one number at a time and it starts from the end of the number and moves forward until it reaches a non zero number
3rd Oct 2018, 10:20 PM
David Aseltine
David Aseltine - avatar
0
Ah, okay, then that's not the problem ... hm.
3rd Oct 2018, 10:21 PM
HonFu
HonFu - avatar
0
Can it be that your int overflows at '13!'? Have you tried to get a larger range by taking a long int?
3rd Oct 2018, 10:35 PM
HonFu
HonFu - avatar
0
ODLNT thank you I switched int fact to double fact and now it is working for a much higher range of numbers
3rd Oct 2018, 10:50 PM
David Aseltine
David Aseltine - avatar
0
ODLNT thats very interesting ill have to try and write a code for that when i have some more time
4th Oct 2018, 12:00 AM
David Aseltine
David Aseltine - avatar