简体   繁体   中英

i didn't understand why " if(number%i ==0) " ->(condition is always true) ... which means this method will always return false

[condition is always true , which means that the method will always return false ][1]

  public class Primenumber {
    public int number ;
    public void saisie(){
        Scanner sc = new Scanner(System.in);
        System.out.print("donnez un un entier : ");
        number = sc.nextInt();
    }
    public boolean isprime(){
        for(int i=1 ; i <= number-1 ; i++ )
            if(number%i ==0)
                return false;
        return true ;
    }
} ```

在第一个循环中, i将为 1,整数 mod 1 始终为 0。您希望从 2 开始。

Start loop from 2 not from 1 .

public boolean isprime(){
    if(number < 2)
       return false
    for(int i=2 ; i <= number-1 ; i++ )
        if(number%i ==0)
            return false;
    return true ;
}

In this line int i=1 you have to change the value of i to 2 .

Why ? At the first run, when i = 1 , any number mod 1 => 0 , because there is no rest.

If you have any number divided by 1 , there is at no time a rest.

So the right code would be:

public class Primenumber {
     public int number ;
     public void saisie(){
         Scanner sc = new Scanner(System.in);
         System.out.print("donnez un un entier : ");
         number = sc.nextInt();
     }
     public boolean isprime(){
         for(int i=2 ; i <= number-1 ; i++ )
             if(number%i ==0)
                 return false;
         return true ;
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM