How to apply "If" & "Else" functions to BigInteger?

1

I have this code in Long working normally:

public static void main(String args[]){

  List<Long> lista = new ArrayList();  

    for(long a = 1; a <= 100; a++){

    if(a%2==0) {}
            else if (a%3==0){}
            else {
             lista.add(a);
               }   
         }
    System.out.println(lista);
   }
}

ImadethisothercodeinBigIntegerforthesamefunction,butdoesnotwork:

publicstaticvoidmain(String[]args){List<BigInteger>lista=newArrayList();BigIntegercomeço=newBigInteger("1");
    BigInteger fim = new BigInteger("100");
    BigInteger n0 = new BigInteger("0");
    BigInteger n2 = new BigInteger("2");
    BigInteger n3 = new BigInteger("3");

for (BigInteger a = começo; a.compareTo(fim) <= 0; a = a.add(BigInteger.ONE)) {

   if (a.divide(n2)==n0){}
   else if (a.divide(n3)==n0){}
   else {
       lista.add(a);
      }
    } 
  System.out.println( lista );
  }
}

    
asked by anonymous 24.02.2017 / 21:58

1 answer

0

You are only using the wrong method. In your original code with long , you used % which is the rest of the division. Already in your code with BigInteger , you are using divide , which makes division and not rest of the division. You should be using the remainder instead.

There is yet another problem. You should use equals instead of == . The reason is the same for which you should not compare% with% s with String , that is, == compares if two objects are in the same memory location, and do not have the same contents.

Additionally, you can also use the == which is much more practical than the constructor that receives valueOf(long) . It is also recommended to use String , a href="http://docs.oracle.com/javase/10/docs/api/java/math/BigInteger.html#ONE"> BigInteger.ZERO and BigInteger.ONE .

Finally, it is not necessary to have BigInteger.TEN s and if s clauses empty, you can always rearrange the corresponding Boolean expression.

Here is your resulting code:

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

class Divisao {
    public static void main(String[] args) {
        List<BigInteger> lista = new ArrayList<>();

        BigInteger começo = BigInteger.ONE;
        BigInteger fim = BigInteger.valueOf(100);
        BigInteger n0 = BigInteger.ZERO;
        BigInteger n2 = BigInteger.valueOf(2);
        BigInteger n3 = BigInteger.valueOf(3);

        for (BigInteger a = começo; a.compareTo(fim) <= 0; a = a.add(BigInteger.ONE)) {
            if (!a.remainder(n2).equals(n0) && !a.remainder(n3).equals(n0)) {
                lista.add(a);
            }
        } 
        System.out.println(lista);
    }
}

Here's the output from it:

[1, 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49, 53, 55, 59, 61, 65, 67, 71, 73, 77, 79, 83, 85, 89, 91, 95, 97]

See here working on ideone.

    
24.02.2017 / 22:12