Problem Statement: Given an integer n, print the pattern.
Example 1:
Output:
1
1 2
1 2 3
1 2 3 5
1 2 3 5 7
Example 2:
Output:
1
1 2
1 2 3
1 2 3 5
1 2 3 5 7
1 2 3 5 7 11
Approach:
Firstly, we need to observe the pattern which is given. After carefully observing it is clear that that the pattern only contains prime numbers except 1, isn't it? So, we know that prime number starts from 2 so we will take a variable let's say k
and initialize it to 2. Now we also know by looking at the pattern the pattern needs to be print until row and column becomes equal to given integer n
. So, we will create an array list for storing the previous row numbers. And we know that the new number is always at last when row and columns are equal. So, we will check for the prime number with the help of function and print it and store in list and will increment k
by 1 with the value obtained from function.
There are two methods used in this approach helper()
and checkPrime()
. helper()
function helps in finding the appropriate prime number with the help of checkPrime() method.
helper(k) takes k as parameter.
Algorithm:
k = 2
helper()
which will help in finding the appropriate next prime number value and store returned value from function in a variable say x
.Code Implementation:
Output:
1 2
1 2 3
1 2 3 5
1 2 3 5 7
Follow up: This approach can be further optimized using Sieve of Eratosthenes. Can you optimize it?
If you want to contribute such articles to solutions2coding.com please click here. Thank you!