The fastest way to find the sum of digits for large numbers

I have a few large numbers (again), and I need to find if the sum of the digits is an even number. I tried this: I find the sum of the digits with the while loop, and then checking if this sum is% 2 0 and it works, but it is too slow for large numbers, because I have given the intervals of numbers, and if the input is 1999999 19999999999, then my program crashes, I can not finish in a time equal to 0.1 seconds.

What to do? Is there an even faster way to do this?

EDIT: entry 1999999 19999999999 means it will start from 1999999 and will check all numbers, as I wrote above, until 19999999999, and because we are talking about large numbers (<2 ^ 30), my program is not worthy.

+3
source share
3 answers

You do not need to summarize the numbers. I think about it. The amount starts from zero, which is usually considered even (although you can use a special case if you want).

Each even digit does not change anything. If the amount was odd, it remains odd, even if it remains even even.

Each odd digit changes the amount from even to odd or odd to even.

So, just count the number of odd digits. If the number is even, then the sum of all numbers will be even. If the number is odd, then the sum of all numbers is odd.

Now you need to do this only for the FIRST number in your range. What you need to do next is figure out how the evenness or oddness of the numbers changes when they are added.

. !

+5

: , n , n + 1 ?

:, @Mark, ... , n + 1 10, .. (n + 1) % 10 == 0. . , (, 199 → 200). ... , , 9 n, , n n + 1. , , , , ...

+2

, - , , - , , , (.. ).

.

- .

:

ASM XOR ,

FORTH ...

+1

Source: https://habr.com/ru/post/1741346/


All Articles