how can i write down a simple c expression that evaluates to the largest multiple of a number n,not greater than a given number m.
c program
Collapse
X
-
Tags: None
-
Originally posted by sekitolekohow can i write down a simple c expression that evaluates to the largest multiple of a number n,not greater than a given number m. -
Simplest (though probably not most efficient) way would be to start with m and test whether n mod m = 0 if it does we have a winner!! If it doesn't then decrement m and start again.
This is no easy feat, and in fact the strength of public key Cryptography, relies on (roughly) this problem being difficult for large m. If you had a nice long list of primes (where the largest prime is the largest prime below m) [p1, p2, p3, p4, p5, p6, ....], however, you could try a slightly different approach:
(Not in any particular languag but the flow of logic is the important thing)
Code:currentDivisor = 1; currentPrime = primeList.start(); while(currentDivisor < m) { if(n % currentPrime ==0) { currentDivisor = currentDivisor * currentPrime; } else { currentPrime = primeList.next(); } }
Comment
-
Originally posted by DeManSimplest (though probably not most efficient) way would be to start with m and test whether n mod m = 0 if it does we have a winner!! If it doesn't then decrement m and start again.
if m mod n == 0 your on to a winner
However if m mod n != 0 then
(m - m mod n) mod n == 0 so (m - m mod n) is your answer.
Actually to avoid an if statement (m - m mod n) is always your answer since if m mod n == 0 then (m - m mod n) == (m - 0) == m.Comment
Comment