Divisible by 6 or 7 but not both
I saw this student posting a problem on her
blog and decided to have a go at it in Java. The problem is to print out the numbers below 100 that are divisible by either 6 or 7 but not both. The naive solution is to just loop through all the numbers below 100 and test them using the % operator. However, that might be inefficient if the limit was, say 10000000 instead of 100, so I tried to do it without using the modulus operator. It turns out that there wasn't really that significant a difference below 100000000. Ah well, here's the code anyway.
public class SixSeven{
public static void main(String args[]){
int adder=1;
int six=0;
int seven=0;
int limit=100;
while(six six+=6;
seven = six + adder;
if(six>limit||seven>limit)
break;
if(adder==7){
adder = 1;
continue;
}
System.out.println(six);
adder++;
if(adder==7)
continue;
System.out.println(seven);
}
}
}
Labels: geek, hacking