jeudi 9 avril 2020

How does Multiple by 3 or 5 in code works?

public class MultiplesOf3Or5 {

     public static int Solution(int number) {

    int result;     
   result = 0;
    if (number > 3)
    {
        int min = 3;
        int count = (number - 1) / 3;
        int max = number - 1;
        while (max % 3 != 0)
        {
            max--;
        }
        int tempResult = count * (min + max) / 2;
        result += tempResult;
    }
    if (number > 5)
    {
        int min = 5;
        int count = (number - 1) / 5;
        int max = number - 1;
        while (max % 5 != 0)
        {
            max--;
        }
        int tempResult = count * (min + max) / 2;
        result += tempResult;
    }
    if (number > 15)
    {
        int min = 15;
        int count = (number - 1) / 15;
        int max = number - 1;
        while (max % 15 != 0)
        {
            max--;
        }
        int tempResult = count * (min + max) / 2;
        result -= tempResult;
    }

    return result;
  }

}

Guys, help me. I having a hard time understanding this code. How does the multiple by 3 or 5 works on this code and to sum all of multiple by 3 and 5 equal to 23? Sorry just found this on google and said that this code is multiple by 3 or 5. It also came to my mind that maybe i have to add something so that i can sum them all. I tried to wrote it on a scratch paper and try to understand what's going on with the code but I didn't really get it. If someone knows, you can explain. I will be glad to know. Thank you.

Aucun commentaire:

Enregistrer un commentaire