I am a student trying to learn programming on my own, getting help from online sources and people like you. I found an exercise online to create a small program that will do this:
Write a program that will read the numbers a and b (type long) and list how many numbers between a and b are divisible by either 2, 3 or 5.
For example:
a=11
b=30
The counter would be 14
, since there are 14
numbers divisible by 2
,3
or 5
in between:
12, 14, 15, 16, 18, 20, 21, 22, 24,25, 26, 27, 28, 30
This is what I have already tried, but it doesn't seem to work. I would need your guidance and help to finish this. Thank you for your time and your hard work in advance.
import java.util.Scanner;
public class V {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long a = sc.nextLong();
long b = sc.nextLong();
for (long c = a; c <= b; c++) {
if (c%2 || c%3 || c%5) {
System.out.println(c);
}
}
}
}
CURRENT STAGE OF THE PROGRAM:
import java.util.Scanner;
public class Test2 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
long a = sc.nextLong();
long b = sc.nextLong();
long count = 0; // counter
for (long c = a; c <= b; c++) {
if (c % 2 == 0 || c % 3 == 0 || c % 5 == 0) {
count++;
System.out.println(c);
}
}
}
}
There is still a thing to do:
Now it lists me the numbers which are divisible by 2,3 or 5. But all I need is one single number that will count how many numbers there is.