Home > Backend Development > C++ > 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
Release: 2023-09-20 08:25:06
forward
1264 people have browsed it

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
Copy after login

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
Copy after login

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
Copy after login

Expected output

Sum = Sum2 + Sum5 - Sum10
Copy after login

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;
}
Copy after login

Output

Sum is 201
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template