Jason arora
Jason arora

Reputation: 550

Calculate and return the value of 3*f+5*b-15*fb in a FizzBuzzProblem

Given: A number is considered fizz if it is divisible by 3. It is considered buzz if it is divisible by 5. It is considered fizzbuzz if it is divisible by both 3 and 5. A fizzbuzz is neither fizz nor buzz. Given two numbers n1 and n2 such that n2>n1, let f be the number of fizz, b be the number of buzz and fb be the number of fizzbuzz between n1 and n2(both n1 and n2 are included).

Calculate and return the value of 3*f+5*b-15*fb?

MyApproach:

I used all conditions given in the question but I am confused how to use this condition "A fizzbuzz is neither fizz nor buzz"

I am getting wrong output may be because of this Can Anyone guide me how to solve the problem.

public int calcFB (int n1, int n2) 
{
    int f=0;
    int b=0;
    int fb=0;
  for(int i=n1;i<=n2;i++)
  {
     if((i%3==0)&&(i%5==0))
     {
       fb++;
     }
     else if(i%3==0)
     {
        f++;
     }
     else if(i%5==0)
     {
        b++;
     }


  }
   return 3*f+5*b+15*fb;

}

For the Input:

 Parameters      Actual Output  Expected Output
'1' '21'         56             18

Upvotes: 0

Views: 124

Answers (2)

paxdiablo
paxdiablo

Reputation: 881413

Your approach is mostly correct. The phrase "A fizzbuzz is neither fizz nor buzz" simply means not to double count numbers in your calculation.

That's because the earlier definitions on their own:

  • A number is considered fizz if it is divisible by 3.
  • It is considered buzz if it is divisible by 5.
  • It is considered fizzbuzz if it is divisible by both 3 and 5.

could be read to (for example) have the number 15 as all of fizz, buzz and fizzbuzz, since 15 is certainly divisible by both 3 and 5

The extra phrase clarifies this point, that multiples of 15 are fizzbuzz only (neither fizz nor buzz). And, in fact, your code already accounts for this phrase since it checks for fizzbuzz first and, if found, moves on to the next number straight away.


The reason you're getting the wrong answer is simply that you're adding 15*fb whereas the specs clearly state you need to subtract that term:

3*f+5*b-15*fb
       ^
       here

If you're adding, you get the result 48 (not 56 as you seem to state in the question, that would need the upper end of the range to be 25 rather than 21). Subtracting will get you the correct answer of 18.

Upvotes: 2

IsaacDorenkamp
IsaacDorenkamp

Reputation: 61

In your return statement, you added 15*fb where in your description of the problem, you said the formula was 3*f+5*b-15*fb. So you need to subtract 15*fb with this return statement:

return 3*f+5*b-15*fb

Upvotes: 2

Related Questions