Home  >  Article  >  Backend Development  >  Translate the following content into Chinese: In C programming, find the sum of numbers within N that can be divided by 2 or 5

Translate the following content into Chinese: In C programming, find the sum of numbers within N that can be divided by 2 or 5

WBOY
WBOYforward
2023-09-20 08:25:061195browse

Translate the following content into Chinese: In C programming, find the sum of numbers within N that can be divided by 2 or 5

The sum of n natural numbers that can be divided by 2 or 5 can be found by finding the sum of all natural numbers within N that can be divided by 2 and the sum of all natural numbers that can be divided by 5 within N. Come and find out. Subtract these two sums by the sum of natural numbers within N that are divisible by 10, and that's what we want. This method is an efficient way to find the sum of large values ​​of n.

Some of you must be thinking of using loops and conditional statements and then adding up all numbers divisible by 2 or 5, but this approach is inefficient as it has time complexity of order n . This means that for larger values ​​of n, the program will run the loop n times. And doing it this way makes the program heavier.

Find the formula for the sum of n natural numbers that can be divisible by 2

Sum2 = ((n / 2) * (4 + (n / 2 - 1) * 2)) / 2

Find the formula for the sum of n natural numbers that can be divisible by 5

Sum5 = ((n / 5) * (10 + (n / 5 - 1) * 5)) / 2

Find the formula for the sum of n natural numbers that can be divisible by 5 Formula for the sum of natural numbers divisible by 10

Sum10 = ((n / 10) * (20 + (n / 10 - 1) * 10)) / 2

Expected output

Sum = Sum2 + Sum5 - Sum10

Example

#include <stdio.h>
int main() {
   int n = 25;
   long int sum2, sum5, sum10;
   sum2 = ((n / 2) * (4 + (n / 2 - 1) * 2)) / 2;
   sum5 = ((n / 5) * (10 + (n / 5 - 1) * 5)) / 2;
   sum10 = ((n / 10) * (20 + (n / 10 - 1) * 10)) / 2;
   long int sum = sum2 + sum5 - sum10;
   printf("Sum is %d", sum);
   return 0;
}

Output

Sum is 201

The above is the detailed content of Translate the following content into Chinese: In C programming, find the sum of numbers within N that can be divided by 2 or 5. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete