i want to print a series using recursion in java - java

You have to print a pattern using recursion. Given a input
N
the pattern looks like this
N
,
a
i
,
a
i
+
1
,
a
i
+
2
,.....,
N
. Where if
a
i
>
0
then
a
i
+
1
=
a
i
−
5
else
a
i
+
1
=
a
i
+
5
. It will be a decreasing sequence from
N
till
a
i
<=
0
and then an increasing sequence till
N
. (See sample test cases for better explanation)
Input format
First line contains an integer
T
denoting number of test cases.
For each of the next
T
lines, each line contains an integer
N
.
Output format
For each test case on a new line, print the required pattern.
Constraints
1
<=
T
<=
6
0
<=
N
<=
2000
Example
Input
2
16
10
Output
16 11 6 1 -4 1 6 11 16
10 5 0 5 10
Sample test case explanation
For the first test case
N=16, it will be a decreasing sequence till the printing number becomes <=0.
16 11 6 1 −4
After this point it will be a increasing sequence till the printing number becomes N
1 6 11 16
So the pattern is 16 11 6 1 −4 1 6 11 16.
My code is below but i got the output as 16,11,6,1,-4 only. Help me to correct this code
import java.util.Scanner;
public class Day3
{
public static void series(int n,boolean b)
{
int temp = n;
boolean flag=b;
System.out.println(temp+" ");
if(flag==true)
temp-=5;
else if(flag==false)
temp+=5;
if(temp<=0)
flag=false;
if(temp<=n)
series(temp,flag);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t>0)
{
int n = sc.nextInt();
series(n,true);
t-=1;
}
}
}

Because 'n' changes in every cases. You must create another variable and keep first 'n' in that, for control if temp smaller than 'n'.
For example
import java.util.Scanner;
public class Day3
{
int firstN = 0; //added that line
public static void series(int n,boolean b)
{
int temp = n;
boolean flag=b;
System.out.println(temp+" ");
if(flag==true)
temp-=5;
else if(flag==false)
temp+=5;
if(temp<=0)
flag=false;
if(temp<=firstN) //changed that line
series(temp,flag);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t>0)
{
int n = sc.nextInt();
firstN = n; //added that line
series(n,true);
t-=1;
}
}
}
Also a little tip;
you can use (flag) for (flag==true)
and (!flag) for (flag==false)

Just FYI : Although this can be solved using recursion, it can be solved more efficiently without using recursion. It is as simple as this:
private static void printSeries(int N) {
int T = N;
while ( T >= 0 ) {
System.out.print(T + " ");
T = T - 5;
}
while ( T <= N ) {
System.out.print(T + " ");
T = T + 5;
}
}

Related

how can i extract last digit from input in java

import java.text.BreakIterator;
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner in= new Scanner(System.in);
System.out.println("nomber");
int n= in.nextInt();
int s= n*n;
int l = (""+s).length();
System.out.println(l);
}
}
how can I extract last digit from input in a simple way. Not so complicated like while loop.... java
Since last digit is also the remainder of dividing by 10, you can use n % 10.
The simplest way to extract last digit is modulo to 10. Example: 123 % 10 = 3
After that, if you want to continue to extract last digit (it's 2 in this case), you should assign number = number /10 that will return the remain of the number.
// Example n = 123
int lastDigit_1 = n % 10; // This will return 3
n = n /10 // This will return 12 because 123 / 10 = 12
int lastDigit2 = n % 10; // This will return 2
n = n /10 // This will return 1
int lastDigit3 = n % 10;
...
To implement the above concept, u should try using while loop for better approach.
Using while:
while(n != 0){
someVariable = n % 10;
// YOUR LOGIC HERE
n = n / 10;
}

Decreasing number pyramid, nested for loop, user input, java

Write a program to produce the following output for any given integer number between
1 and 9 inclusive.
Enter an integer value [1..9]: 6
1
12
123
1234
12345
123456
666666
66666
6666
666
66
6
I have done the top half but I can not figure out the bottom with the repeating user input.
package lab7;
import java.util.Scanner;
public class problem5 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Input an integer between 1 and 9");
int input = scan.nextInt();
while (input <= 9) {
for (int i = 1; i <= input; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
break;
}
}
}
Expected result: included at the top; actual result so far (input of 5):
1
12
123
1234
12345
You're pretty close. You have a for loop that covers the first half of the output you want. You can add a second for loop to handle the second half of the output.
This is pretty similar to the first loop, but has a few small differences:
instead of the loop variable starting at 1 and increasing, this one starts at input and decreases each time through (i-- instead of i++)
instead of printing any of the loop variables (i or j), it prints the input value ("6" in your example)
for (int i = input; i > 0; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(input);
}
System.out.println();
}
If I run that code locally – so your for loop, then this for loop, then the break statement – this is the output:
Input an integer between 1 and 9
6
1
12
123
1234
12345
123456
666666
66666
6666
666
66
6
I would prefer a more efficient algorithm, your current approach is O(n2); consider the digits '1' - '9'; if we store them in a String then we can take a simple substring of that String for each line at the top (for example, "123456789".substring(0, 3) -> "123") that can be used to generate the top through successive calls to substring. We can use a similar approach to build the bottom; use an array of all possible rows and iteratively call substring. Finally, don't forget to validate that input is between one and nine inclusive. Something like,
Scanner scan = new Scanner(System.in);
String digits = "123456789";
String[] btm = { "1", "22", "333", "4444", "55555",
"666666", "7777777", "88888888", "999999999" };
System.out.println("Input an integer between 1 and 9");
int input = scan.nextInt();
if (input < 1 || input > 9) {
System.err.printf("Invalid input: %d%n", input);
System.exit(1);
}
for (int i = 0; i < input; i++) {
System.out.println(digits.substring(0, i + 1));
}
for (int i = input - 1; i >= 0; i--) {
System.out.println(btm[input - 1].substring(0, i + 1));
}

How do i recognize 2 digits as separated digits?

So basically the assignment says i need to get a number 'n' from the user and for all the numbers between 1 to 'n' code the program to print all the numbers divided by 3 without residue && print ONLY the numbers that both (or one) of their digits equal to 5 or less, for example if the user give 22 the programs prints 3,12,21.
thats what ive done by now (the place i putted a question mark is where im having hard time to figure out what to do) so this code in not compiled yet :
public static void main(String[] args) {
Scanner get = new Scanner(System.in);
int num;
System.out.println("Enter A Random Number: ");
num = get.nextInt();
for (int i=1;i>0 && i<=num;i++) {
if (i%3==0 && ?)
System.out.println(i);
I'm a bit confused about the second part of your question but based on the first part and what I got from the second part ( that the sum of the digits of numbers that is equal or less to 5 should only be printed )
Here is the code for your program : (It should work perfectly, update me if you find any problems)
public static void main(String[] args) {
Scanner get = new Scanner(System.in);
int num;
System.out.println("User please enter a number of your choice : ");
num = get.nextInt();
for(int x = 1 ; x < num ; x++){
String number = ""+ x ;
int sum = 0 ;
for(int i = 0 ; i < number.length() ; i ++ ){
sum +=number.charAt(i)-'0' ; }
if(x % 3 == 0 && sum <= 5){
System.out.println(x) ; }
sum = 0 ;
}
}
divided by 3 without residue
If you understand what "without residue" means, then I assume you are familiar with modulo arithmetic. In programming, we have the modulo operator % which returns the remainder from a division. So 25 % 8 evaluates to 1. You can use this to get the digits of a number 21 % 10 evalutes to 1 which is exactly the ones digit. To get the the tens digit, we need to divide by 10 first 21 / 10 % 10 evaluates to 2. This works because integer division throws away the remainder.
This will do. So, you have to go through every digit so, I converted it into a string and then matched the regex for 1 to 5 on that character and then put it back in another string and it solves it.
public static void main(String[] args) {
Scanner get = new Scanner(System.in);
int num;
System.out.println("Enter A Random Number: ");
num =Integer.parseInt(get.nextLine());
for(int i =1;i<=num; i++){
if(i%3==0){
String input = Integer.toString(i);
String toPrint = "";
for(int j =0 ; j<input.length();j++){
if(Character.toString(input.charAt(j)).matches("^[1-5]$")){
toPrint+=Character.toString(input.charAt(j));
}
}
//check the length to avoid cases like 30,60 etc.
if(input.length()==toPrint.length()){
System.out.println(toPrint);
}
}
}
}

SPOJ Prime generator in JAVA

Input
The input begins with the number t of test cases in a single line
(t<=10). In each of the next t lines there are two numbers m and n (1
<= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n,
one number per line, test cases separated by an empty line.
Example
Input: 2 1 10 3 5
Output: 2 3 5 7
3 5
I wrote this one:
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = 0;
long n1=0;
long n2=0;
while(i<=n){
n1 = sc.nextLong();
n2 = sc.nextLong();
if(n1==1)
{
n1++;
}
if((n1-n2)<=100000){
for(long j=n1;j<=n2;j++){
int count = 0;
for(long k=2;k<=j/2;k++){
if(j%k==0){
count = 1;
}
}
if(count==0){
System.out.println(j);
}
}
}
}
}
}
It is working fine in my system
But it is showing time exceeded on submission.

How to generate a right angle Fibonacci Series pyramid in Java?

I want to generate an output like this :-
0
0 1
0 1 1
0 1 1 2
0 1 1 2 3
0 1 1 2 3 5
However, i am trying in this way to achieve , but some piece of logic is missing which i am unable to decipher.
Here's what i am trying :-
import java.util.Scanner;
class Fibonacci
{
public static void main(String arr[])
{
System.out.println("Enter a no.");
Scanner input=new Scanner(System.in);
int num=input.nextInt();
int x=0,y=1;
for(int i=0;i<=num;i++)
{
for(int j=0;j<i;j++)
{
System.out.print(j);
}
System.out.println("");
}
}
}
And it generates the output like this (consider num=6)
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
What logic is required to get the desired output ? Would be thankful if anyone can explain me this :)
Thanks in advance !!
You need to change logic of inner loop like this by adding two previous number to current number and swap them like this.
import java.util.Scanner;
class Fibonacci
{
public static void main(String arr[])
{
int x = 0, y = 0, c = 0;
System.out.println("Enter a no.");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
for (int count = 0; count < num; count++) {
System.out.print(0);
x = 0;
y = 1;
c = 0;
for (int i = 1; i <= count; i++) {
c = x + y;
y = x;
x = c;
System.out.print(" " + c);
}
System.out.println();
}
}
}
First two numbers 0 and 1 are given , no need to caculate .
Use a String to save previous line string .
Caculate next numbers , add it into your previous line string .
Here is an example :
int x = 0 , y = 1;
int num = 6;
System.out.println("0");
System.out.println("0 1");
String str = "0 1";
for(int i = 2 ; i < num ; i ++){
int amt = x + y ;
x = y;
y = amt;
str += " " + amt;
System.out.println(str);
}
In a Fibonacci series only the first two numbers are provided which are 0 and 1. The next number of the series are calculated by adding the last two numbers. The series is limited by the user by providing the number of integers it wants in the series.
Logic: The logic behind creating a Fibonacci series is to add the two integers and save them in a new variable z = x+y and then replace the first integer value by the second integer and second integer value by their sum to move one step ahead in the series x=y adn y=z.
In your problem you want the series to be printed in a right angled triangle so you need to save the series that is already printed in a string
int n = 10;
System.out.println("0\n");
System.out.println("0 1\n");
int x = 0, y=1;
int i=2, z=0;
String str = "0 1";
while(i!=10)
{
z = x+y;
str += " " + z;
x=y;
y=z;
i++;
System.out.println(str);
}
Hope this helps

Categories

Resources