Input is 0-5 million
Find all numbers within the input that are: Odd
Divisible by 17
Output those numbers
This is what I have for now, not sure how to proceed:
for (int i = 0; i < 5000001; i ) {
if (i % 2==0){
I'm sure that the for loop needs to be used, not sure how to find if it's divisible by 17. There was a similar question on here already, however it was in python.
CodePudding user response:
If we go with the given code in question, we can achieve the desired output as below,
for (int i = 0; i < 5000001; i ) {
if( i % 2 == 0 && i % 17 == 0){
System.out.println(i);
}
}
But it is not efficient, What I can think of, to make it efficient is,
The first odd number divisible by 17 will be 17 itself, so instead of starting from 0, start from 17.
Then, observer the table of 17 -> 17, 34, 51, 68, 85, 102....
You will see, you are getting odd even numbers alternatively, that is because odd even = odd.
So now, start from 17 and add 17*2 (i.e 34) every time to get only odd numbers that are divisible by 17.
Like this,
for(int i = 17, i < 5000001; i = 34){
System.out.println(i);
}
CodePudding user response:
Here is the code :-
int num = 0;
while(num 17 <= 5000000){
num = num 17;
if(num % 2 == 0){
System.out.print(num " ");
}
}
System.out.println("Done");