JAVA - Netbeans - FOR Cycle

1

I'm starting in java language, with netbeans. I do some exercises, I just can not understand how the next cycle works:

if (num<=1){
        return false;
    }else{
        int prueba;         
        int contador=0;
        prueba=(int)Math.sqrt(num);
        for (;prueba>1;prueba--){
            if (num%prueba==0){
                contador+=1;
            }
        }
        return contador < 1;
    }
    
asked by Diego Espinosa 08.12.2018 в 17:28
source

1 answer

2

TL; DR: You are looking at whether prueba has dividers.

Classic for has 3 "sections":

  • definition and initialization of variables;

  • an expression that returns boolean that indicates whether to continue iterating;

  • actions to be taken at the end of each loop.

In your case

for (;prueba>1;prueba--){
  • there is no definition or initialization of variables, variables defined before are used;

  • will iterate as long as% co_of% is greater than 1;

  • after each iteration, 1 will be subtracted from prueba (so at some point prueba will end up being prueba or less).

The condition

if (num%prueba==0){

Check if the modulo operation 1 (the "remainder" of the division) returns 0. If so, % is a divisor of prueba .

Finally,

prueba=(int)Math.sqrt(num);

If num has some divisor, some of these must be between prueba and square root of 1 in fact the exact half of the divisors, except in the case of perfect squares. When starting prueba with this value, if there is a divisor the value of prueba will be contador or greater, if it does not exist it will be 1 .

    
answered by 08.12.2018 / 18:19
source