I finally finished code for a problem I was given in my AP CompSci class just now. The purpose is to "Write a function that takes and integer argument. Return true if the number is divisible by all of its digits (if a digit is 0 return false) else retuen false" Can you guys tell me how badly I messed this up-
public static boolean divstuff(int num)
{
int newnum=num; //sets initial value because otherwise I get errors
int length = String.valueOf(num).length(); //Gets length of num
boolean tf=false; //use this for determining if class returns true/false because otherwise errors
for(int count=0; count<=length; count++)
{
if (count==length) //if count is equivelent to the length of the number then everything is divisible
{
tf=true;
break;
}
else //still numbers that need to be divided
{
int temp=newnum%10; //get's last number
if (temp==0) //Because I don't want divided by zero
break; //A number can't be divided by it's factors if it has zero
else
if ((num%temp)!=0) //Divides num by one of it's numbers, and checks if modulo is zero
break;
else
newnum=newnum/10; //get's new last number
}
}
if (tf==true)
return true;
else return false;
}
Also are there are any ways to improve the efficiency of this? And are there any ways to input a number to break this?
Efficiency: As soon as you reach a digit 0, or if the number is not divisible, you can return false instead of break.
Instead of doing a count by length, you can do a while(newnum > 0){}, or even better, a custom for
You'd get:
public static boolean divstuff(int num)
{
if(!num) return false; // return false if we get a 0
for(int newnum = num; newnum > 0; newnum /= 10)
{
int temp = newnum % 10; //gets last number
if (temp == 0 || (num % temp) != 0) return false; //Because I don't want divided by zero, then Divides num by one of it's numbers, and checks if modulo is zero
newnum = newnum / 10; //gets new last number
}
return true;
}
But then in your own words, of course