Hi guys, In this article, We will discuss Odd Numbers, related mathematical problems and Programming way using Java.
Formulas:-
Odd Numbers:-
- The sum of the first ’N’ Odd Numbers is N².
- The sum of the ’N’ Odd Numbers is [(n(a+l))/2].
Where n=((Last term-First term)/Difference of CN)+1,n is No. of Numbers, a is the first term, l is the last term, and CN is a Consecutive Number.
Problems:-
Q. Find the sum of the first 30 odd numbers.
Ans. n²=>30²=>900.
In programming way.
import java.util.Scanner;
public class SumOfFirstOddNums {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter any Natural Number:");
int natural_number = scanner.nextInt();//30
int result = 0;
for (int i = 0; i <=2*natural_number; i++) {
if (i % 2 != 0) {
result = result + i;
}
}
System.out.println(result+" is the sum of the first "+natural_number+" odd numbers.");
//result=900.
}
}
output:
Enter any Natural Number:
30
900 is the sum of the first 30 odd numbers.
Q. Find the sum of odd numbers up to 15.
Ans.n=13, n²=13²=>169.
In Programming way.
import java.util.Scanner;
public class SumOfOddNumsUpto {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter any Natural Number:");
int natural_number = scanner.nextInt();//15
int result = 0;
for (int i = 1; i < 2 * natural_number-1; i++) {
if (i % 2 != 0) {
result = result + i;
}
}
System.out.println(result+" the sum of odd numbers up to "+natural_number);
//result=196
}
}
output:
Enter any Natural Number:
15
196 the sum of odd numbers up to 15
Q. Find the sum of odd numbers from 25 to 75.
Ans. First term=25, Last term=75 => n=((last term-first term)/Diff of CN)+1 =>((75–25)/2)+1 => (50/2)+1=19. n=26.
N=(n(a+l))/2 where n=26, a=25, l=75. =>(26(25+75))/2 =>(26(100))/2 =>13(100) =>1300.
In Programming way.
import java.util.Scanner;
public class SumofOddNums {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter First Natural Number:");
int natural_number1 = scanner.nextInt();//25
int result1 = 0;
for (int i = 0; i <natural_number1; i++) {
if (i % 2 != 0) {
result1 = result1 + i;
}
}
System.out.println("Enter second Natural Number:");
int natural_number2 = scanner.nextInt();//75
int result2 = 0;
for (int i = 0; i <=natural_number2; i++) {
if (i % 2 != 0) {
result2 = result2 + i;
}
}
int N=result2-result1;
System.out.println(N+" is the sum of the odd numbers from "+natural_number1+" to "+natural_number2);//1300
}
}
output:
Enter any First Natural Number:
25
Enter any Second Natural Number:
75
1300 is the sum of the odd numbers from 25 to 75.
Conclusion:-
Continue in the next article. Thanks for reading Please Follow Ram.