Program for n-th odd number
Last Updated :
20 Aug, 2022
Given a number n, print the nth odd number. The 1st odd number is 1, 2nd is 3, and so on.
Examples:
Input : 3
Output : 5
First three odd numbers are 1, 3, 5, ..
Input : 5
Output : 9
First 5 odd numbers are 1, 3, 5, 7, 9, ..
The nth odd number is given by the formula 2*n-1.
C++
#include <bits/stdc++.h>
using namespace std;
int nthOdd( int n)
{
return (2 * n - 1);
}
int main()
{
int n = 10;
cout << nthOdd(n);
return 0;
}
|
Java
class GFG
{
static int nthOdd( int n)
{
return ( 2 * n - 1 );
}
public static void main(String [] args)
{
int n = 10 ;
System.out.println(nthOdd(n));
}
}
|
Python3
def nthOdd(n):
return ( 2 * n - 1 )
if __name__ = = '__main__' :
n = 10
print (nthOdd(n))
|
C#
using System;
class GFG
{
static int nthOdd( int n)
{
return (2 * n - 1);
}
public static void Main()
{
int n = 10;
Console.WriteLine(nthOdd(n));
}
}
|
PHP
<?php
function nthOdd( $n )
{
return (2 * $n - 1);
}
$n = 10;
echo nthOdd( $n );
?>
|
Javascript
<script>
function nthOdd(n)
{
return (2 * n - 1);
}
var n = 10;
document.write( nthOdd(n));
</script>
|
Output:
19
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...