How to divide a number stored in a string and check if it is divisible by 495?

1

For example a number that does not fit into a int and I store it in a String .

How do I see if it is divisible by 495?

    
asked by anonymous 09.10.2016 / 12:36

2 answers

3

Why do not you use the BigInteger class to handle with these numbers?

You can use the BigInteger#mod :

public static boolean divisivel(BigInteger numero, String divisor) {
    return numero.mod(new BigInteger(divisor)).equals(BigInteger.ZERO);
}

The above function should get a BigInteger and a string with the divisor number, see an example:

public static void main (String[] args) throws java.lang.Exception
{
    System.out.println(divisivel(new BigInteger("495"), "495")); // true
    System.out.println(divisivel(new BigInteger("496"), "495")); // false
}

Complete code:

import java.io.*;
import java.math.BigInteger;

class Ideone
{
    public static boolean divisivel(BigInteger numero, String divisor) {
        return numero.mod(new BigInteger(divisor)).equals(BigInteger.ZERO);
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(divisivel(new BigInteger("495"), "495")); // true
        System.out.println(divisivel(new BigInteger("496"), "495")); // false
    }
}

See DEMO

    
09.10.2016 / 13:19
0

To turn string into int or long you can do so ...

Scanner s = new Scanner(System.in);
String str = s.nextLine();
try {
   int inteiro = Integer.parseInt(str);
   long longo = Long.parseDouble(str);
} catch (NumberFormatException e) {
   System.out.println("Numero com formato errado!");
}

Here your variable integer or long will have the value of your string, now only know if the division of it by 495 has zero remainder.

if(i % 495 ==0){
System.out.println("É divisível");
}
    
13.10.2016 / 00:32