Question

Suppose one has a function, prod(x), that returns the product of a sequence of numbers, x.

If the number of operands in x can be arbitrarily large, how might one think about reducing the time to compute the product of x by ceasing multiplication when zero is encountered? Is this something that mature compilers and interpreters already do?

If one is writing one's own prod(x) function, what is the best approach? Does it ever make sense to do something like if 0 in x then return(0) else multiply(x)?

For example, if x = 1,0,3,4,...,-4,9, one shouldn't need to continue multiplying past the second term, right?

Était-ce utile?

La solution 2

In general: Compiler optimizations are mostly done on the given source code. You're talking about optimization on run-time data, which compilers (normally) won't do. This means that you have to write these optimizations yourself.

In this case: You can indeed stop when there's a 0.

Autres conseils

Any multiplication with 0 returns 0, so you'd check if there's a 0 in a sequence and just return 0.

Since the multiplication operation commutes, you can evaluate the terms in any order. If you were to have a sorted sequence of numbers, you could simply see if the first item is zero.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top