Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C Program for n-th odd number
Given a number N, we have to find the N-th odd number. Odd numbers are the numbers which are not completely divisible by 2 and their remainder is not zero, like 1, 3, 5, 7, 9, etc.
If we closely observe the sequence of odd numbers, we can represent them mathematically as −
1st odd number: (2*1)-1 = 1 2nd odd number: (2*2)-1 = 3 3rd odd number: (2*3)-1 = 5 4th odd number: (2*4)-1 = 7 ... Nth odd number: (2*N)-1
So, to solve the problem we can simply multiply the number N with 2 and subtract 1 from the result.
Syntax
nth_odd_number = (2 * n) - 1
Examples
Input: 4 Output: 7 Explanation: The 4th odd number in sequence 1, 3, 5, 7... Input: 10 Output: 19 Explanation: The 10th odd number using formula (2*10)-1 = 19
Algorithm
START STEP 1 -> Declare and assign an integer 'n' STEP 2 -> Calculate nth odd number using formula: n*2-1 STEP 3 -> Print the result STOP
Example
#include <stdio.h>
int main() {
int n = 10;
int nth_odd;
// Calculate nth odd number using formula
nth_odd = (n * 2) - 1;
printf("The %dth odd number is: %d<br>", n, nth_odd);
// Let's verify with first few odd numbers
printf("\nFirst 5 odd numbers:<br>");
for(int i = 1; i <= 5; i++) {
printf("%d ", (i * 2) - 1);
}
printf("<br>");
return 0;
}
Output
The 10th odd number is: 19 First 5 odd numbers: 1 3 5 7 9
Key Points
- The formula
(2*N)-1directly gives the Nth odd number - Time complexity is O(1) as it uses a direct mathematical formula
- Space complexity is O(1) as no extra space is required
Conclusion
Finding the Nth odd number is efficiently solved using the mathematical formula (2*N)-1. This approach provides constant time complexity and is much faster than iterative methods.
Advertisements
