I’m working on a very basic Android app, and I need to update a progress bar in correspondence to the loops traversal to find if an entered number is prime. The entered number must be of long data type. The plan was to traverse a loop from i = 2 to sqrt(number), and divide the entered number by i each iteration. If i divides the number, then the loop ends, and we decide it is NOT a prime.
Otherwise, the loop keeps going, meanwhile updating the progress. Here is a snippet of the pertinent code:
protected Void doInBackground(Long... params) {
String message;
Intent intent = new Intent(MainActivity.this, DisplayMessageActivity.class);
long lim = (long)Math.sqrt(params[0]);
for (int i = 2; i <= lim; i++) {
if (params[0] % i == 0) {
message = params[0] + " is not prime!";
int myProgressFinal = 100;
publishProgress(myProgressFinal);
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
return null;
}
else {
int myProgress = i/lim * 100;
publishProgress(myProgress);
if (isCancelled())
return null;
}
}
message = params[0] + " is prime!";
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
return null;
}
}
My problem spot is the else statement:
else {
int myProgress = i/lim * 100;
publishProgress(myProgress);
I have an integer i for the loop, showing my progression through the loop, and to find the percentage that I’ve advanced, I would have to divide by the max amount of the loop (lim = sqrt(number)) and then multiply by 100 to get the proper percentage. However, I can’t do this b/c myProgress is an integer, but lim is a long, and cannot be changed to int. Even if I make lim an int, I still have integer division giving me a wrong value (0 * 100). It won’t let me typecast one of them to double b/c myProgress has to be int in order to be passed through publishProgress(). Any suggestions?
For a start, if ‘i’ is going to range all the way up to lim, ‘i’ will need to be a long as well. Otherwise, once ‘i’ hits Integer.MAX_VALUE, the next iteration is going to cause overflow.
I believe you want to declare i as a long, and in your else statement do
“int myProgress = (int)((((double)i)/lim) * 100)”