Reputation: 1139
I have a problem with a program that prints a list of prime numbers, but as modulus is ignored, the program is not working. Can someone find something wrong here?
import java.util.Scanner;
public class Primos {
public static void main(String[] args){
Scanner entrada = new Scanner(System.in);
System.out.println("Dame el numero hasta el cual sacare primos");
int hasta = entrada.nextInt();
for(int actual = 2 ; actual <= hasta ; actual++){
boolean primo = true;
for(int probando = 2 ; probando < actual ; probando ++){
double valor = (double)actual/(double)probando;
System.out.println("1." +valor);
valor = valor % 10;
System.out.println("2." +valor);
if(valor == 0){
primo = false;
break;
}
}
if(primo)
System.out.println("El numero " + actual + " es primo");
}
}
}
prints
Dame el numero hasta el cual sacare primos
3
El numero 2 es primo
1.1.5 <before mod
2.1.5 < after mod
El numero 3 es primo
Upvotes: 0
Views: 97
Reputation: 21101
As mentioned in assylias's comment, 1.5 % 10 = 1.5
Replace your statement
valor = valor % 10;
with
valor = valor - (long) valor;
Upvotes: 1
Reputation: 109613
It should be
int valor = actual % probando;
As actual / probando
gives the integer division (rounding down / truncating the fraction),
actual % probando
gives the remainder of such division:
12 / 7 = 1
12 % 7 = 5
(p / q) * q + (p % q) == p
If value is 0, probando
is a divisor of actual
. What you meant.
Upvotes: 0
Reputation: 17165
Your logic is wrong. A number is prime if no number less than it divide evenly into it (ie number % factor == 0 means it's not prime)
public static void main(String[] args){
Scanner entrada = new Scanner(System.in);
System.out.println("Dame el numero hasta el cual sacare primos");
int hasta = entrada.nextInt();
boolean primo = true;
for(int factor = 2 ; primo && factor < hasta/2 ; factor++){
primo = hasta % factor != 0;
}
if(primo)
System.out.println("El numero " + actual + " es primo");
}
}
Upvotes: 0
Reputation: 280138
In your first iteration, the nested for loop doesn't execute because actual=2
is not smaller than probando=2
.
for (int probando = 2; probando < actual; probando++) {
So your next iteration occurs where actual=3
and probando=2
, printing the values you see.
Upvotes: 0