Home >Backend Development >C++ >Mean square of natural numbers?

Mean square of natural numbers?

WBOY
WBOYforward
2023-09-20 22:29:121575browse

Mean square of natural numbers?

The average of the squares of natural numbers is calculated by adding all the squares of n natural numbers and then dividing by that number.

Example

The first 2 natural numbers are 2.5,

12 22 = 5 => 5/2 = 2.5.

There are two calculation methods in programming -

  • Use loops
  • Use formulas
Use loops to calculate squares of natural numbers The average of

This logic works by finding the square of all natural numbers. Find the square of each by looping from 1 to n and add to the sum variable. Then divide that sum by n.

Program for calculating the sum of squares of natural numbers -

Sample code

Real-time demonstration

#include <stdio.h>
int main() {
   int n = 2;
   float sum = 0;
   for (int i = 1; i <= n; i++) {
      sum = sum + (i * i);
   }
   float average = sum/n;
   printf("The average of the square of %d natural numbers is %f", n,average);
   return 0;
}

Output

The average of the square of 2 natural numbers is 2.500000

Use the formula to calculate the mean of the squares of natural numbers.

There are mathematical formulas to make calculations easy. To calculate the sum of squares of natural numbers, the formula is ' n*(n 1)*((2*n) 1)/6' Divide it by the number n to get the formula: ' (n 1)* ((2*n) 1 )/6'.

Program for finding the sum of squares of natural numbers -

Sample code

Live demonstration

#include <stdio.h>
int main() {
   int n = 2;
   float average = ((n+1)*((2*n)+1)/6);
   printf("The average of the square of %d natural numbers is %f", n,average);
   return 0;
}

Output

The average of the square of 2 natural numbers is 2.500000

The above is the detailed content of Mean square of natural numbers?. 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