How to check if my integer can be divided by 3 as below:
for(int i=0; i<24; i++){
//here, how to check if "i" can be divided by 3 completely(e.g. 3, 6, 15)?
}
Use the modulo operator.
if(i % 3 == 0)
Also see Modulo operation at Wikipedia
If you are using a loop, you can use the fact that every third number can be divided by 3.
for(int i = 0; i < 24; i += 3) {
System.out.println(i + " can be divided by 3");
System.out.println((i+1) + " cannot be divided by 3");
System.out.println((i+2) + " cannnot be divided by 3");
}
This avoids the need for a modulo and cuts the number of loops by a factor of 3.
Use the MOD operator
for(int i=0; i<24; i++){
if( i%3 == 0 )
// It is divisible by 3
}
Well, what you could do (it might be a bit faster; it is faster on my machine) is:
boolean canBeDevidedBy3 = ((int) (i * 0x55555556L >> 30) & 3) == 0;
instead of
boolean canBeDevidedBy3 = (i % 3) == 0;
However, the multiplication trick only works for -2 <= i <= 1610612735. This answer was inspired by this optimization question. But if I can give you a tip: use (i % 3) == 0. It's so much simpler, and will always work.
Check the remainder of i devided by 3
if (i % 3 == 0) {}
inside the loop:
if (i%3 == 0)
// it can be divided by 3
% is called "mod" or "modulus" and gives you the remainder when dividing two numbers.
These are all true:
6 % 3 == 0
7 % 3 == 1
7 % 4 == 3
if( i % 3 == 0 )
The % operator delivers you the rest of the division i / 3
if( i % 3 == 0 ){
System.out.println("can be divided by 3");
}else{
System.out.println("cant divide by 3");
}
Is this question for real?
Related
Beginner here. For my coding class, we have an assignment that requires us to print numbers 1-20, but configure it so that it only outputs even numbers. Here is what I have so far but I'm quite stuck. He says to put an if statement and use the "%" operator but I've no idea where to put them.
int counter = 1;
System.out.println("Part 2 - Even Numbers");
while (counter <= 20)
{
//if (counter
System.out.printf("%d ", counter);
counter++;
} // end while loop
Instructions for assignment
My Output
CORRECT Output
if(counter % 2 == 0){
System.out.printf("%d ", counter);
}
counter++;
% operator is mod operator, if counter % 2 == 0 , then counter is an even number
% is an arithmetic operator, it is called MODULO.
Modulo operator returns the remainder of 2 numbers. In this case, we use a modulo to find out whether a number is even or odd.
odd%2 returns 1
even%2 returns 0
The while loop loops through the first 20 elements. So we put an if statement before printing the element. If the counter is an even number i.e (counter%2 == 0) we print that.
This is the code that prints even numbers:
int counter = 0;
System.out.println("Part 2 - Even Numbers");
while (counter <= 20)
{
if (counter%2 == 0){
System.out.printf("%d ", counter);
}
counter++;
} // end while loop
This can also be done without using MODULO operator:
int counter = 0;
System.out.println("Part 2 - Even Numbers");
while (counter <= 20)
{
System.out.printf("%d ", counter);
counter+=2;
} // end while loop
use fori
public static void main(String[] args) {
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
}
% is the remainder operation
I have two questions about this of code.
Can someone explain me, what the if statement is doing exactly. I know that count has to increment every time the test is true, but I'm not sure what the this n % i == 0 is doing.
My second question is, how can I print the return statement's answer on the console?
int n = 10;
countFactors(n);
}
public static int countFactors(int n){
int count = 0;
for (int i = 1; i <= n; i++){
if (n % i == 0) //this line
count++;
}
return count;
}
}
It count the number of divisor in your range 1-n so for example :
if n = 10 the result will be 4 because there are 4 divisor:
1
2
5
10
and about how you print in console :
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
count++;
System.out.println(i);
}
}
System.out.println("Number or disivor = " + count);
You can learn here : Table of divisors
Well, as the name of the method suggests, the count represents the number of divisors that n has.
The if statement tests the following: Is n divisible by i?. in other words: Is n/i a whole number?
if you were to use:
if(n%i == 1)
instead, then it would count the numbers for which: n/i has a remainder of 1.
in order to print the return statement, you can add this line just before the return:
public static int countFactors(int n){
int count = 0;
for (int i = 1; i <= n; i++){
if (n % i == 0)
count++;
}
System.out.println(count);//adding this
return count;
}
The % operator (known as the remainder or Modulus operator) basically divides a number by another and gives you the remainder and nothing else. For instance, if you do 4 % 2, it would give you 0 because 2 goes into 4 evenly. If you would do 4 % 3 it would give you 1 because that's the remainder of 4 / 3. Also look at this website: http://www.cafeaulait.org/course/week2/15.html
The countFactors method loops 1 to n and includes n. If you do 10 % 1, you would get 0 because one goes into 10 evenly so the count would be incremented.
/* when I run this code there is no error in fact output generated is also correct but I want to know what is the logical error in this code? please can any one explain what is the logical error. */
class abc
{
public static void main(String arg[]){
int sum=0;
//for-loop for numbers 50-250
for(int i=50;i<251;i++){
// condition to check if number should be divided by 3 and not divided by 9
if(i%3==0 & i%9!=0){
//individual number which are selected in loop
System.out.println(i);
//adding values of array so that total sum can be calculated
sum=sum+i;
}
}
//final display output for the code
System.out.println("the sum of intergers from 50 to 250 that are multiples of 3 and not divisible by 9 \n"+sum);
}
}
My philosophy is "less code == less bugs":
int sum = IntStream.rangeClosed(50, 250)
.filter(i -> i % 3 == 0)
.filter(i -> i % 9 != 0)
.sum();
One line. Easy to read and understand. No bugs.
Change this:
if(i%3==0 & i%9!=0){
to this:
if(i%3==0 && i%9!=0){
& = bitwise and operator
&& = logical operator
Difference between & and && in Java?
The only problems I saw were:
The variable sum was undeclared
Use && in place of &
int sum = 0;
for (int i = 50; i <= 250; i++) {
if (i % 3 == 0 && i % 9 != 0) {
System.out.println(i);
sum = sum + i;
}
}
System.out.println("the sum of intergers from 50 to 250 that are multiples of 3 and not divisible by 9 \n" + sum);
Well, instead of touching every single value from 50 to 250 like you would do here for(int i=50;i<251;i++), you can consider something like this...
int i = 48;
int sum = 0;
while(i < 250) {
i += 3;
if(i%9 != 0)
sum += i;
}
This is somewhat optimized in the sense that I am skipping over values that I know are not possible candidates.
But, there is a much bigger issue in your code. The following code block prints true, sure. But, it is a bad idea to depend on the & since that is not its job. The & is for bitwise AND whereas the && is for logical AND, which is what you are trying to do.
boolean t = true;
boolean f = false;
System.out.println(f&t);
Why?
In Java, if it is a && operation, as soon as you find the first false, you are sure that the expression will evaluate to false. Meanwhile, in your implementation, it would need to evaluate both sides. f&t will evaluate to false, but the JVM would need to look at both the f and t variables. Meanwhile, on using &&, it wouldn't even need to look at the t.
I have this assignment:
Write a Java program which finds all the odd numbers from 1 - 50 which are divisible by 7, but sums only the EVEN numbers which are divisible by 9.
Print sum.
Print count of odd numbers which are divisible by 7.
Print count of even numbers which are divisible by 9 within that range.
This is my code:
int sNumber = 0;
for(int aNumber= 1; aNumber <= 50; aNumber++)
{
if (aNumber % 7 == 0)
if(aNumber % 2 == 1)
System.out.println("These are odd"+" "+ aNumber);
}
for(int bNumber=1 ; bNumber < 50; bNumber++)
{
if (bNumber % 9 == 0)
if(bNumber%2 == 0)
System.out.println("These are even"+" "+bNumber);
}
I'm stuck with putting bNumbers into sum form, any help?
The idea is to start with creating a variable to store the sum. It has to start from 0. Whenever you find an even number that is divisible by 9, you add it to the sum. By the end of your for loop when you have iterated through all of your numbers, you would have the total of all your even numbers that are divisible by 9 in your variable sum.
In my code below, I have also used two integers countEven and countOdd to keep track of the number of relevant numbers found. counteven increments by one whenever an even number that is divisible by 9 is found and countodd increments by one whenever an odd number that is divisible by 7 is found.
Note: it is always good practice to use braces for all for, if, while and other similar statements / loops, even if the block contains only one line of code to execute.
int countEven = 0, countOdd = 0, sum = 0;
for(int i= 1; i <= 50; i++){
if ((i % 7 == 0) && (i % 2 == 1)) {
System.out.println("This is an odd number that is divisible by 7: " + i);
countOdd++;
}
if ((i % 9 == 0) && (i % 2 == 0)) {
System.out.println("This is an even number that is divisible by 9: " + i);
countEven++;
sum += i;
}
}
System.out.println("These are " + countOdd " odd numbers thare are divisible by 7 and " + countEven + " even numbers that are divisible by 9.");
System.out.println("Sum of even numbers that are divisible by 9: " + sum);
You don't need two loops to do this, it can be done in one.
Check the current number vs. the two conditions you have:
if(i % 2 == 0 && i % 7 == 0)
sumOfEven += i;
if(i % 2 != 0 && i % 9 == 0)
countOdd++;
You need to simply add this to your second loop sNumber += bNumber;
Also consider using AND operator instead of nested if statement.
int sNumber = 0;
for (int aNumber = 1; aNumber <= 50; aNumber++) {
if (aNumber % 7 == 0 && aNumber % 2 == 1) {
System.out.println("These are odd" + " " + aNumber);
}
}
for (int bNumber = 1; bNumber <= 50; bNumber++) {
if (bNumber % 7 == 0 && bNumber % 2 == 1) {
System.out.println("These are even" + " " + bNumber);
sNumber += bNumber;
}
}
System.out.println("Sum of even numbers" + " " + sNumber);
Hope this helps.
I'm doing a basic Java tutorial and below is the question.
Write a method that prints the numbers from 1 to 100. But for multiples of three print ÒFizzÓ instead of the number,and for the multiples of five print ÒBuzzÓ. For numbers which are multiples of both three and five print ÒFizzBuzzÓ."
My code is below
public static void fizzBuzz(){
for(int i = 0; i < 101; i= i +1 ){
System.out.println(i);
if (i%15 == 0){
System.out.println("ÒFizzBuzzÓ");
}else if (i % 3 == 0){
System.out.println("ÒBuzzÓ");
}else if (i % 5 == 0){
System.out.println("ÒFizzÓ");
}
}
}
It seemingly runs fine, but on closer inspection of the output, the "Fizz" and "Buzz" lines are printed AFTER the relevant numbers and are not printed as a replacement of the numbers
For example, I get the below
9
ÒBuzzÓ
10
ÒFizzÓ
11
12
ÒBuzzÓ
13
14
15
ÒFizzBuzzÓ
16
How do I get the relevant numbers to be replaced by the correct string statements instead of what I currently have? I only managed to find tips on converting strings to integers, but not replacement of integers to strings on SO, so I would appreciate any help :)
Move printing of number in else part of your if else ladder as like:
for(int i = 1; i < 101; i= i +1 ){
if (i%15 == 0){
System.out.println("ÒFizzBuzzÓ");
}else if (i % 3 == 0){
System.out.println("ÒBuzzÓ");
}else if (i % 5 == 0){
System.out.println("ÒFizzÓ");
} else {
System.out.println(i);
}
}