My logical program is not giving the correct output? - java

Question:
The Utopian tree goes through 2 cycles of growth every year. The first growth cycle occurs during the spring, when it doubles in height. The second growth cycle occurs during the summer, when its height increases by 1 meter.
Now, a new Utopian tree sapling is planted at the onset of the spring. Its height is 1 meter. Can you find the height of the tree after N growth cycles?
Input Format
The first line contains an integer, T, the number of test cases.
T lines follow. Each line contains an integer, N, that denotes the number of cycles for that test case.
Constraints
1 <= T <= 10
0 <= N <= 60
Output Format
For each test case, print the height of the Utopian tree after N cycles.
//FINALLY, HOPE so .. WHAT QUESTION IS SAYING..
INITIALLY VALUE IS 1 .. IF SPRING OCCURS.. IT'S VALUE WILL BE DOUBLED.. THAT MEANS .. IT WILL BE MULTIPLIED BY 2.. BUT IF SUMMER OCCUR IT'S VALUE WILL BE ADDED BY 1...
If i give input:
2 //here 2 is the number of question..
0
1
So, Output must be:
1
2
Another example,
sample of output:
2
3
4
So, Sample of input will be:
6
7
HOPE SO.. YOU UNDERSTAND WHAT QUESTION IS ASKING, HERE NOW WE HAVE TO MAKE A PROGRAM INTO JAVA....
Okay as further i made a program for this..
package com.logical03;
import java.util.Scanner;
public class MainProgram{
public static void main(String[] args){
int num=1;
int[] array=new int[100];
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements=in.nextInt();
System.out.println("Enter the values now: ");
for(int i=1; i<=n_Elements; i++){
array[i]=in.nextInt();
}
for(int i=1; i<=n_Elements; i++){
if(array[i]==0){
System.out.println("\n1");
}
else{
for(int j=1; j<=array[i]; j++){
if(j%2!=0){
num=num*2;
}
else{
num=num+1;
}
}
System.out.println(num);
}
}
}
}
As i run into here .. it adds the second number of question into my output.. Suppose..
If i give input as:
2
3
4
So, output must suppose to be:
6
7
Which is correct!!
But My program gives the output as:
6
27 //which is incorrect..becoz it adds the sum of above number :(

Mistake - int num = 1; should be declared in inside parent loop to refresh it's value.
public static void main(String[] args) {
int[] array = new int[100];
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements = in.nextInt();
System.out.println("Enter the values now: ");
for (int i = 1 ; i <= n_Elements ; i++) {
array[i] = in.nextInt();
}
for (int i = 1 ; i <= n_Elements ; i++) {
int num = 1;
if (array[i] == 0) {
System.out.println("\n1");
} else {
for (int j = 1 ; j <= array[i] ; j++) {
if (j % 2 != 0) {
num = num * 2;
} else {
num = num + 1;
}
}
System.out.println(num);
}
}
}
Output
Enter the number of Questions:
2
Enter the values now:
3
4
6
7

My approach is to take on account that first cycle (2 * height) occurs on odds indexes, and second cicle (1 + height) occurs on even indexes, from 1 to n (inclusive), starting index 0 is always 1.
return IntStream.rangeClosed(1, n)
.reduce(1, (acc, idx) -> idx % 2 != 0 ? acc * 2 : acc + 1);

This is my first contribution, only learning to code and solve algorithms, I had to find a workable solution with simple to follow code credit to http://www.javainterview.net/HackerRank/utopian-tree
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
//receive input
Scanner in = new Scanner(System.in);
//no of test cases
int T=in.nextInt();
//no of cycles
int[] N = new int[T];
for(int i=0;i<T;i++){
N[i]=in.nextInt();
}
int height=1;
for(int i=0;i<N.length;i++){
height=1;
for(int j=1;j<=N[i];j++){
if((j%2) ==1)
height=height*2;
else
height++;
}
System.out.println(height);
}
}
}//this the end of the class

Related

Needed to create a function thet recieves an array of 2 degits nums , Switch between the digits and print but got an error

Write a function that receives double-digit numbers, until a number that is not double-digit is received.
• For each number received the program will generate a reverse number and print it. For example : 67 will be printed 76.
• The program will print a count of some of the received numbers thet contains the digit 5 ​​in the digit
Unity (right digit).
I researched the error I got a couple of times but couldn't solve it, if you guys can help much appreciated.
public static void switchInput() {
Scanner star = new Scanner(System.in);
int x=0 , temp=0 , y=1 , i , b=0;
x= star.nextInt();
int[] Switch = new int[x];
//input
for(i=0 ; i<y ; i++){
System.out.println("insert num "+ y + " :");
temp= star.nextInt();
x++;
y++;
Switch[i]=temp;
if(temp<10||temp>99) {
y=i;
}
if(temp%10==5) {
b++;
}
temp=0;
}
star.close();
//Switch
int j , temp2 , temp3=0;
for(j=0 ; j<x ; j++) {
temp3=Switch[j]/10;
temp2=Switch[j]%10;
temp3+=temp2*10;
Switch[j]=0;
Switch[j]=temp3;
}
//print
for(int z = 0;z<x-1;z++) {
System.out.print(" "+Switch[z]+ " ");
}
System.out.println("Number of times 5 was used is : " + b);
}
I got the error :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 44 out of bounds for length 44
at hagashaShadi.q1.switchInput(q1.java:37)
at hagashaShadi.q1.main(q1.java:67)
See x= star.nextInt(); here your providing size of array suppose its x=3
which means int[] Switch = new int[3]; but when you are running for loop you are getting like this Switch[4] which is out of bound for the array of size 3. So solution is to use either while loop and insert only when it satisfy the condition and it should break once it cross size of array or if you want to use for loop then break out of loop when i>length-of-array
Have a look at the below code for more understanding
public static void switchInput() {
Scanner star = new Scanner(System.in);
int i=0 , countDigit=0;
List<Integer> numList=new ArrayList<>();
boolean isTwoDigitNumber=true;
//Insert all input number of 2 digit
while(isTwoDigitNumber)
{
System.out.println("insert num "+ (i+1)+ " :");
int temp= star.nextInt();
if(temp%10==5){
countDigit++;
}
if(temp>10&&temp<99) {
numList.add(temp);
i++;
}else {
isTwoDigitNumber=false;
}
}
star.close();
//Switch
//reverse the number and print
for(int j=0 ; j<numList.size() ; j++) {
int num = numList.get(j), reversed = 0;
//System.out.println("Original Number: " + num);
// run loop until num becomes 0
while(num != 0) {
// get last digit from num
int digit = num % 10;
reversed = reversed * 10 + digit;
// remove the last digit from num
num /= 10;
}
System.out.println("reverse Number: " + reversed);
}
//print number of times 5
System.out.println("Number of times 5 was used is : "+countDigit);
}

time limit error exceeding due to modulo(10,9)+7 maybe?

There are N soldiers located on our X-AXIS. The point at which a soldier is located also has some number of bombs.
The war is near and every soldier wants to communicate with every other soldier.
If the i-th soldier has b number of bombs and is located at position X then the cost of communicating with any other soldier j having c number of bombs located at position Y is defined as |X-Y|*max(b,c).
Find the sum of costs of communication if every soldier wants to communicate with every other soldier.
NOTE :- You have to consider pair(i,j) only once in sum of costs.
Input Format:
First line consists of number of test cases T. Each test case consists of three lines. The first line indicates the number of soldiers (N). The second line indicates the coordinates of the N soldiers ( X[i] ). The third line contains the number of bombs at every soldiers location ( B[i] ) . The x-coordinates needn't be in increasing order in the input.
Constraints
1 <= T <= 20 1 <= N <= 200000 1 <= X[i] <= 1000000000 1 <= B[i] <= 10000
Output Format:
The total cost modulo 10^9+7.
Sample Input
1
3
1 3 6
10 20 30
Sample Output
280
Explanation
there are 3 pairs (1,2) -> cost = abs(3-1) * 20 = 40 (1,3) -> cost = abs(1-6) * 30 = 150 (2,3) -> cost = abs(3-6) * 30 = 90 sum = 40 + 150 + 90 = 280
I'm handling modulo (10^9+7) and everything using brute force but getting tle code below its also working for the case above however it one of those annoying tle/type conversion type of problem. Any response is truly appreciated-
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
int T=sc.nextInt();
for(int ctr=0;ctr<T;ctr++)
{
int N=sc.nextInt();
long [] x= new long[N];
long [] b= new long[N];
for(int i=0;i<N;i++)
{
x[i]=sc.nextLong();
}
for(int i=0;i<N;i++)
{
b[i]=sc.nextInt();
}
int cost=0;
double v;
for(int i=0;i<N-1;i++)
{
for(int j=i+1;j<N;j++)
{
v= x[i]%(Math.pow(10,9)+7)-x[j]%(Math.pow(10,9)+7);
v=Math.abs(v)%(Math.pow(10,9)+7);
cost+= v*Math.max(b[i],b[j]);
}
}
System.out.println(cost);
}
} }
As suggested by #Erwin, don't use Math.pow() to calculate (10^9)+7 thrice in each iteration of the for loop. Instead, take it outside the loop (maybe define it as a constant) and then execute your operations.
Also, you are doing modulo with (10^9)+7 constant twice in your operation. Are you sure that is the intended operation? You are doing it in the first computation of v and then again in the second computation of v. If you need it only for the final cost, you can remove it from the first step.
Here is my code that you can try:
import java.util.*;
public class Main {
public static void main(String args[]) {
double moduloNumber = (Math.pow(10,9)+7);
Scanner sc= new Scanner(System.in);
System.out.print("Enter the Number of Test Cases (1 <= T <= 20): ");
int T=sc.nextInt();
for(int ctr=0;ctr<T;ctr++)
{
System.out.print("\nEnter the Number of Soldiers (1 <= N <= 200000): ");
int N=sc.nextInt();
long [] x= new long[N];
long [] b= new long[N];
for(int i=0;i<N;i++)
{
System.out.print("Enter the Position of Soldier " + (i+1) + " (1 <= X[i] <= 1000000000): ");
x[i]=sc.nextLong();
}
for(int i=0;i<N;i++)
{
System.out.print("Enter the Number of Bombs with Soldier " + (i+1) + " (1 <= B[i] <= 10000): ");
b[i]=sc.nextInt();
}
int cost=0;
double v;
for(int i=0;i<N-1;i++)
{
for(int j=i+1;j<N;j++)
{
v=(x[i]-x[j]);
v=Math.abs(v)%(moduloNumber);
cost+= v*Math.max(b[i],b[j]);
}
}
System.out.println(cost);
}
}
}
I just added some print statements and moved the modulo constant outside the loop to reduce computation costs. You can check if this solves the purpose.
Regards,
AJ

why does displayed number goes above the input number in java?

Currently, I am doing an assignment on displaying all odd numbers up to a user inputted specific odd number. The requirement is to include the input number, however, I don't understand why does the code always goes to the next Odd number compared to what user inputted. Please help.
import java.util.Scanner;
public class OddNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Pls enter an odd number you want to finish to: ");
int capp_number = input.nextInt();
int startingNumber = 1;
for(int i = 0; i < capp_number; i+= 2){
startingNumber += 2;
System.out.println(startingNumber);
}
This is because i starts at 0 (It is even), and you are checking to see if it is less than capp_number (which should be odd), and then adding two to i. startingNumber starts at 1, so it is odd. So if the user enters 5 it will go like:
Iteration 1:
i (0) < 5 ? Yes:
print startingNumber+2
output: 3
i == 2
Iteration 2:
i (2) < 5 ? Yes:
print startingNumber +2
output: 5
i == 4
Iteration 3:
i (4) < 5 ? Yes:
print startingNumber +2
output: 7
i == 6
Iteration 4
i (6) < 5 No:
end loop
To fix this, start i at one:
for(int i = 1; i < capp_number; i+= 2)
Sorry, but why did you write this ?
while(startingNumber < capp_number);
i agree with a previous answer and think that there is no reason for this line. And also you should correct your loop as it was also mentioned in previous answer:for(int i = 0; i < capp_number; i+= 2)
Try this. You needed to initialise i to 1 within the for-loop. 1 is an odd number so instead of starting with an even number (0), you look for every odd number.
For example, if you start at 1: 1+2=3, 3+2=5, 5+2=7.... and so on.
For example, if you start at 0: 0+2=2, 2+2=4, 4+2=6.... and so on.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Pls enter an odd number you want to finish to: ");
int capp_number = input.nextInt();
int startingNumber = 1;
for(int i = 1; i < capp_number; i += 2){
startingNumber += 2;
System.out.println(startingNumber);
}

Java addition with power of a number program wrong result

In my program Logic is like:--
Input Addition with Output(result)
2 3 5
3 3+4 10
4 3+4+4 15
5 3+4+4+4 20
6 3+4+4+4+4 25
So, I have made:--
import java.util.Scanner;
public class Addition {
public static void main( String[] args) {
#SuppressWarnings("resource")
Scanner s = new Scanner(System.in);
int result=0;
System.out.print("Enter a number: ");
int inputNumber = s.nextInt();
if(inputNumber==2){
result = inputNumber+3;
}
else{
Addition c=new Addition();
int j = inputNumber-2;
int power=c.pow(4,j);
result = inputNumber+3+power;
}
System.out.print(result);
}
int pow(int c, int d)
{
int n=1;
for(int i=0;i<d;i++)
{
n=c*n;
}
return n;
}
}
In this program I am getting result:--
Input Output(result)
2 5
3 10
4 23
5 72
why? What Am I doing wrong??
You're confusing 'power of' with multiplication.
int power=c.pow(4,j);
should simply be:
int power= 4 * j;
You are calculating j correctly, its value will be 1 for inputNumber 3, 2 for inputNumber 4 and so on ...But You are not using it correctly. Note we are not adding powers of 4(4,16,64..), we are simply adding multiples of 4 in increasing order(4,8,12,..). So you should be adding 4*j to calculate the result
Change your code as follows:-
int j = inputNumber-2;
int multiple=4*j;
result = inputNumber+3+multiple;

Numbers to stop at the user's input

How do I make my program to stop at the user's input?
Here is my code:
public class H {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input x: ");
int x = input.nextInt();
for (int i = 0; i < x; i++) {
if (i < x)
System.out.print(printFib(i) + " ");
else if (i > x)
break;
}
}
public static int printFib(int number) {
if (number == 0 || number == 1)
return number;
else
return printFib(number - 1) + printFib(number - 2);
}
}
So, if I enter 10 my program should stop before the number. Example:
Input: 10
Output: 0 1 1 2 3 5 8
But instead I get 0 1 1 2 3 5 8 13 21 34
How can I fix it?
int x = input.nextInt();
int fib = 0;
while (fib < x){
System.out.print(printFib(fib)+ " ");
fib++;
}
}
Don't use a for loop which right now you're using to print out Fibonacci numbers until the number of items printed is less than the entered number. Instead use a while loop that stops when the Fibonacci number itself is greater than the entered number.
Since this is likely homework, I'm just going to give this suggestion and not a code solution, but please give a solution a try, and if still stuck, come back with questions.
Pseudocode
Get value of x
create fibonacci variable and assign it 0
while fibonacci is less than x
display current fibonacci number
calculate next fibonacci number and place in variable
end while loop
public class H {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input x: ");
int x = input.nextInt();
int i = 0;
while ( printFib(i) <= x ) {
System.out.print(printFib(i) + " ");
i ++ ;
}
}
public static int printFib(int number) {
if (number == 0 || number == 1)
return number;
else
return printFib(number - 1) + printFib(number - 2);
}
}
While the number return from the printFib() method is less than and equal to the user input, it then runs the method. I've tried the code and it works.

Categories