Hello how can i check the divisibility of a number without using % / +...
I am new at coding so hope someone can help
I think my code sucks ..i read forums and this is the best i can do

import java.util.Scanner;


public class Divbythree {


    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.println("Enter A Number");
        Scanner keyboard =new Scanner(System.in);
        int Numero = keyboard.nextInt();
        int newNumero = Numero;


        while (newNumero > 0){

            newNumero -= 3;
            System.out.println("1");
                //return newNumero == 0;
            }   

        while (newNumero < 0){
            newNumero += 3;
            System.out.println("2");

        }


    }

}

One way to test if "a" is divisible by "b" simply subtract "b" from "a" until you get a negative number or zero.

You can also test divisiblity using bit operations. To test if something is diisible by 2 do:

if(a & 1 == 0)  //checks if there is a 1 in the last position of the binary number.

to test if something is divisible by 3 you can so something like this:

public boolean divisibleBy3(int n) {
    if (n < 0){
        n = -n;  //if it is a negative number make it posirive otherwise the test will fail
    }else if (n == 0) {
        return true;
    }

    while (n > 3) {
        int d = 0;

        while (n > 0) {
            d += n & 3;  //add last 2 bits of n to d
            n = n >> 2;  //shift n 2 bits to the right
        }

        n = d;
    }

    return n == 3;
}

Edited 3 Years Ago by DarkLightning7

divisibilty ? by what ?

if your looking for odd/even number check you can use bit-wise operations : all even numbers will have 0 in their lowest order bit , whereas odd ones will have 1. check for that , and youll get your answers.

Edited 3 Years Ago by somjit{}

If I wanted to know if 10 was divisible by 3 without using division, I'd subtract 3 repeatedly:

10 - 3 = 7
7 - 3 = 4
4 - 3 = 1

The remainder is 1 -- a number that is smaller than three, but it's not zero. So 10 is not divisible by 3.

I would probably write a program to do something much like what I just did above.

while(dividend>0)
    dividend-=divisor;

if(dividend==0) //is divisible;
else //is not divisible;

p.s. put a divide by zero check in the beginning

Edited 3 Years Ago by cool_zephyr

Thanks everyone for the replies..sorry for the late view here.i already solve it 2days ago..i do something like JeffGrigg does..

This article has been dead for over six months. Start a new discussion instead.