I've written a method that should return the numbers of prime numbers in a given range:
public static int numberOfPrim(int up){ // Returns amount of primnumbers from 0 to up
if(up<=0){
return 0;
}
int primAmount = 0;
for(int i = 1; i<=up ; i++){
if(checkIfPrim(i) == true){
primAmount++;
}
}
return primAmount;
}
public static boolean checkIfPrim(int number){ // If number is prim -> return true
if (number < 2){
return false;
}
boolean prim = true;
if(number == 2){
return prim;
}
boolean[] con = new boolean[number];
for(int i = 2; i < number; i++){
if(number %i == 0) {
con[i] = true;
}
}
for(int j = 0; j < number; j++){
if(con[j] == true){
prim = false;
}
}
return prim;
}
The code is working like I want it to. For example, numberOfPrim(10)
should return 4
(2, 3, 5, 7). I'm just asking if there are any locations where I can improve my code, like shorten it or if there are any other possibilities to write such a method.