(After a few detailed changes :)
If you have only 2 voters, you can only generate the following percentages for candidates A and B:
0+100, 100+0, or 50+50
If you have 3 voters, you have
0+100, 100+0, 33.33+66.67, 66.67+33.33 [notice the rounding]
So this is a fun problem about fractions.
If you can make 25%, then you should have at least 4 people (so you can make 1/4, since 1/2 and 1/3 will not cut it). You can do this with a larger one (i.e. 2/8 = 25%), but the problem requires the smallest value.
However, more interesting fractions require numbers greater than 1 in the numerator:
2/5 = 40%
Since you cannot get this with anything other than 2 or more in the numerator (1 / x will never cut it off).
You can compare at each step and increase the numerator or denominator, which is much more efficient than iterating over the entire sample space for j, and then increasing i;
i.e. if you have a percentage of 3%, checking decisions all the way 96/99, 97/99, 98/99 before even getting to x / 100 is a waste of time. Instead, you can increase the numerator or denominator based on how well your current assumption is fulfilled (more or less)
int max = 5000; //we only need to go half-way at most. public int minVoters (double onePercentage) { double checkPercentage = onePercentage; if (onePercentage > 50.0) checkPercentage = 100-onePercentage; //get the smaller percentage value double i=1; double j=1; //arguments of Math.round must be double or float double temp = 0; while (j<max || i<max-1) { //we can go all the way to 4999/5000 for the lesser value temp = (i/j)*100; temp = Math.round(temp); temp = temp/100; if (temp == checkPercentage) return j; else if (temp > checkPercentage) //we passed up our value and need to increase the denominator j++; else if (temp < checkPercentage) //we are too low and increase the numerator i++; } return 0; //no such solution }
A step-by-step example for finding a denominator that can give 55%
55/100 = 11/20 100-55 = 45 = 9/20 (checkPercentage will be 45.0) 1/1 100.0% 1/2 50.00% 1/3 33.33% 2/3 66.67% 2/4 50.00% 2/5 40.00% 3/5 60.00% 3/6 50.00% 3/7 42.86% (too low, increase numerator) 4/7 57.14% (too high, increase denominator) 4/8 50.00% 4/9 44.44% 5/9 55.56% 5/10 50.00% 5/11 45.45% 6/11 54.54% 6/12 50.00% 6/13 46.15% 6/14 42.86% 7/14 50.00% 7/15 46.67% 7/16 43.75% 8/16 50.00% 8/17 47.06% 8/19 42.11% 9/19 47.37% 9/20 45.00% <-bingo
The good thing about this method is that it only takes steps (i + j) , where i is the numerator and j is the denominator.