Horje
Average of odd numbers till a given odd number

Given an odd number n, find the average of odd numbers from 1 to n.
Examples: 
 

Input : n = 9
Output : 5
Explanation
(1 + 3 + 5 + 7 + 9)/5 
= 25/5 
= 5

Input : n = 221
Output : 111

 

Method 1 We can calculate average by adding each odd numbers till n and then dividing sum by count.
Below is the implementation of the approach. 
 

C

<?php
// Program to find average of odd
// numbers till a given odd number.
 
// Function to calculate the
// average of odd numbers
function averageOdd($n)
{
    if ($n % 2 == 0)
    {
        echo("Invalid Input");
        return -1;
    }
 
    $sum = 0;
    $count = 0;
    while ($n >= 1)
    {
 
        // count odd numbers
        $count++;
 
        // store the sum of
        // odd numbers
        $sum += $n;
 
        $n = $n - 2;
    }
    return $sum / $count;
}
 
    // Driver Code
    $n = 15;
    echo(averageOdd($n));
     
// This code is contributed by vt_m.
?>

Javascript

<?php
// Program to find average of odd
// numbers till a given odd number.
 
// Function to calculate the
// average of odd numbers
function averageOdd( $n)
{
    if ($n % 2 == 0)
    {
        echo("Invalid Input");
        return -1;
    }
 
    return ($n + 1) / 2;
}
 
    // Driver Code
    $n = 15;
    echo(averageOdd($n));
     
// This code is contributed by vt_m.
?>

Javascript

<script>
 
// javascript Program to find average of odd numbers
// till a given odd number.
 
// Function to calculate the average
// of odd numbers
function averageOdd( n)
{
    if (n % 2 == 0) {
        document.write("Invalid Input");
        return -1;
    }
 
    return (n + 1) / 2;
}
 
// driver function
    let n = 15;
    document.write( averageOdd(n));
     
// This code is contributed by todaysgaurav
 
</script>

Output: 

8

Time complexity: O(1) since performing constant operations

Space Complexity: O(1) since using constant variables

 




Reffered: https://www.geeksforgeeks.org


Mathematical

Related
Sum of fifth powers of the first n natural numbers Sum of fifth powers of the first n natural numbers
Program to compare two fractions Program to compare two fractions
Find the distance covered to collect items at equal distances Find the distance covered to collect items at equal distances
Addition and Subtraction of Matrix using pthreads Addition and Subtraction of Matrix using pthreads
Pernicious number Pernicious number

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
15