Faced this question in my interview.
What I answerred is that:
-
divide 1b numbers into 10 group
-
Use threadpool to create one thread for each group, 10 totally
-
each thread sum up the result for the group passed and retrun the value
-
use Barrier to sum up all results after 10 threads end, return the final value
My doubt is what’s the expected answer for this question ?
And if it’s running in single-cpu (no multi-thread mode), should single thread be faster than multi-thread ?
Thanks a lot.
A trick question, perhaps – to see if you can think outside the box you’re given?
If they’re consecutive, as noted in the title, and they begin with n, then:
This works for n up to somewhere around a billion – after that it will overflow.
Needless to say, I don’t see how multithreading would be of any benefit at all!