Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find what range a number is in

Tags:

java

I have folders named like this:

"1-500"
"501-1000"
"1001-1500"
"1501-2000"
"2501-3000"
etc....

Given an Id such as 1777 how can I find the name of the folder it belongs in?

I am using Java, but your answer can be pseudocode.

Thanks!

like image 823
joe Avatar asked Dec 13 '22 17:12

joe


1 Answers

Here is how:

// Folder 0: 1-500
// Folder 1: 501-1000
// Folder 2: 1001-1500
// ...

int n = 1777;
int folder = (n-1) / 500;

System.out.printf("%d belongs to folder %d - %d",
                  n, folder * 500 + 1, (folder+1) * 500);

Output:

1777 belongs to folder 1501 - 2000

The integer division will take care of the "flooring" required to get the right folder-index. Be careful to include the - 1. Otherwise, n = 500 will end up in group 1 (instead of 0).

like image 114
aioobe Avatar answered Dec 28 '22 23:12

aioobe