Problem:
Generate the first n terms of the sequence 1 2 4 8 16 32 .... without using multiplication.
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
//This class is defined to generate
//the sequence 1 2 4 8 16 32 .... without using multiplication
public class GeneratingTheFirstNTermsOfSequence {
static int n = 0;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the No. of terms in series : ");
n = s.nextInt();
generateTheSequence();
s.close();
}
private static void generateTheSequence(){
List<Integer> series = new ArrayList<Integer>();
series.add(1);
System.out.print("The series is: ");
for(int i = 1; i<=n; i++){
series.add(series.get(i-1) + series.get(i-1));
}
System.out.print(series + " ");
}
}
Output:
Enter the No. of terms in series :
10
The series is: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
Generate the first n terms of the sequence 1 2 4 8 16 32 .... without using multiplication.
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
//This class is defined to generate
//the sequence 1 2 4 8 16 32 .... without using multiplication
public class GeneratingTheFirstNTermsOfSequence {
static int n = 0;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the No. of terms in series : ");
n = s.nextInt();
generateTheSequence();
s.close();
}
private static void generateTheSequence(){
List<Integer> series = new ArrayList<Integer>();
series.add(1);
System.out.print("The series is: ");
for(int i = 1; i<=n; i++){
series.add(series.get(i-1) + series.get(i-1));
}
System.out.print(series + " ");
}
}
Enter the No. of terms in series :
10
The series is: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
No comments:
Post a Comment