Sum to determine the largest multiple of 5 at 1000
I am currently trying to get a function to work in a Java application that I am making, however I do not know how to implement this in one line.
I know I can do something line by line (not really, but roughly):
while(i<995){ i=i+5 }
However, I really want to implement it all in one line, for example, in one
static int highestMult = *the equation*
I would not use this specifically for the highest multiple of 5 in 1000, however, on my own research, I could not find the desired solution for this particular case, so this is an example.
The examples I have previously found tend to be about finding only the highest multiplier that does not combine the highest multiplier and the limit.
If this is not knowledge from the back of the head, it would also be very helpful to understand the logic of how you came to the solution, it could save me for getting stuck on similar problems in the future.
Thank,
source to share
If c
is the bottom number (1000 in your case) and m
several (5 in your case), then
((c - 1) / m) * m
- one of the methods. (Note to purists: you don't really need the outer brackets, but I include them for clarity.)
Here I am using integer arithmetic to force the ((c - 1) / m)
floor integer truncation . Multiplying this result by m
means that the final value is a multiple of the value m
. Make sure c
both m
are integer types, or it won't work (unless you say explicitly, which isn't so elegant).
It's undefined for c < 1
andm < 1
source to share
try:
int number=5;
int limit=999;
int i=limit-(limit%number);
where 999 - limit - 1
% - reminder
(999%5)=4
if we remove the reminder from the limit, we get it:
999-4=995
we could use limit=1000
, but the result could be 1000 too
a reminder is a very useful thing for programming: D
for number > 0
andlimit >=0
source to share