How this program works

0

In class, we perform the following program, used to calculate the first n prime numbers of some amount that the user enters by keyboard, but I have not understood the teacher well, I am new to this, thank you very much.

    Scanner sc = new Scanner (System.in);
    int li, suma=0;
    int cont = 0;
    System.out.println("Ingrese la longitud de los numeros primos a sumar");
    li= sc.nextInt();

    for(int i = 2; i <= li; i++)
    {
        cont = 0;
        for (int j = 1; j <= i; j++)
        {
            if(i % j == 0)
            {
                if(j == i)
                cont++;
            }
        }
        if(cont== 2 )
        {
                    suma= suma + i;
        } 
    }
    System.out.print(suma + " ");
    
asked by Axwell Duarte 11.10.2018 в 12:20
source

1 answer

0

A prime number is one that is not divisible by any number, other than 1 and the same number. Well, in the exercise that you put li is your number you want to see if it's cousin or not.

Within the for(int i = 2; i <= li; i++) main you will go from 2 to your number li to thus go through all the existing numbers in that range and see which will be cousins.

Then, in for (int j = 1; j <= i; j++) try to divide each number i by all the number below it, from 1 to i .

In the next part, see if the rest of the division between the numbers is 0, otherwise it will imply that i is not divisible by j . In such a way that if the rest gives 0, that is, it is divisible, it will enter the condition and increase the counter in only one when j equals i . Taking the account of how many prime numbers we carry as it increases i .

        if(i % j == 0)
        {
            if(j == i)
            cont++;
        }
    
answered by 11.10.2018 в 12:45