Home > database >  How do i count the numbers in a given range who's digits sum is divisible by 3
How do i count the numbers in a given range who's digits sum is divisible by 3

Time:09-26

For example if we take 139 141 then The numbers are 139, 140 and 141. Their sum of digits is 13, 5 and 6 respectively. So, only 141 is the number that has its sum of digits divisible by 3.

CodePudding user response:

This may be cheating, but if a number is divisible by 3, so is the sum of its digits. This means you don't really need to sum the digits, you could just check if the number is divisible by 3 directly:

int countSumDigitsDivisibleByThree(int minRange, intMaxRange) {
    int count = 0;
    for (int i = minRange; i <= maxRange;   i) {
        if (i % 3 == 0) {
              count;
        }
    }
    return count;
}

CodePudding user response:

What you'd want to do is to iterate over each one of the numbers and sum up its digits, then check if the sum is divisible by 3. I would've done something like this -

int getSumOfDigits(int num){
    int sum = 0;
    while (num > 0){
        sum  = num % 10;
        num /= 10;
    }
    return sum;
}

int main(){
    int count = 0;
    for (int i = START_OF_RANGE; i <= END_OF_RANGE; i  ){
        if (sumOfDigits(i) % 3 == 0){
            count  ;
        }
    }
    // count is the number of numbers whose sum of digits is divisible by 3.
    return 0;
}
  •  Tags:  
  • c
  • Related