How to check if the sum of 8 files with unlimited natural numbers stored in them is divisible by 8?

I had this question in an interview, and, as expected, I could not answer it. I gave the interviewer a rude approach, which was:

  • Add numbers to each file.
  • Sum the numbers in each file and finally check to see if it divides by 8.

At the same time, I told him about the shortcomings of such an approach as Integer overflow and memory problems.

In any case, I tried to think, but did not succeed, because so far I have not encountered such problems.

How can I solve the above problem and how to develop my thinking process to solve such problems? are there any resources that i could use?

+4
source share
4 answers

Due to the nature of this problem, you will need to check every number in the files. This means that brute force is the only way to do this. However, there are ways to make it more memory efficient and less prone to memory leaks. The following is a breakdown of a simple algorithm to reduce the complexity of the space in the pseudo-code:

Read n integers into array
buffer[ len(array) ] = int array
total = 0

for integer i in array:
    if total % 8 == 0:
        total = 0
        remove all elements in buffer from array
    else
        buffer.append(i)
        total += i
    fi
end for

, , 8, . , 8, , . , , 8. , - O (n). , , .

, . - , ( ) . , n m 8, f (n% 8) + (m% 8) == 0,8. : 5 3, 17 15, 12 12.

, , , O (n), , .

+1

, , k. .

-, , , . 8 ( 0 to 7) , (i * array [i], 0 7) 8.

, , . , 8, , 8. , 8, reset 0. , 0- , 8. , (i * array [i], 1 7), , 8.

Init array[8] by all 0.

while (there is number remain) 
    read a number tmp
    array[tmp % 8]++;
    if (array[tmp%8] == 8)
        array[tmp%8] = 0
sum = 0
for (i from 1 to 7)
    sum += array[i] * i
if sum % 8 == 0
    output yes
else
    output no
+1

, , % 8 . , , 8.

, 8, :

8, 3 8.

, - . @greybeard .

0

…how to develop my thinking process to solve problems
, . : .
(/ - , - . SE () & .)

-, , , - : .
, ( , , 2 ( , ))
( , , , ).
"", ( - , - , gazillion: ( ) ), - , , , ).
, , .

0

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


All Articles