Java addition with power of a number program wrong result - java

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;

Related

Extracting a number in Java isn't working as expected

This program is supposed to print the numbers (indiviual digits) in a number
`
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int number = sc.nextInt();
int Size = 0;
String Conversion = Integer.toString(number);
Size = Conversion.length();
int n = 0;
while (n <= Size){
int d = number%10;
int power = Size - 2;
number = (number/(10^(power)));
System.out.println(d);
n += 1;
}
}
}
`
Really Appreciate for Anyone for Took time to help me.
Thanks
For some reason I get
1
9
3.
instead of
1
3
4
using the debugger gives me some hint, Specifically this block `
number = (number/(10^(power)));
`
for second iteration the value is +4 than expected, 3.
for third Its okay.
changing and adding +4 on that block gives
1
3
7
4
Found it !!
Credit OH GOD SPIDERS, tkausl
Solution 1 : Instead of using carrot characters in
number = (number/(10^(power)));
use Math.pow function.
Solution 2 :
Don't use (number/(10^(power))
instead just divide by 10

Using Strings and Double Arrays

I'm brand new to programming, so please bear with me. I need to create a program using while loops, one String array, and three double arrays. My output should be something like this:
java Average 4
Joe 3 5 2
Tim 4 1 5
Jane 6 3 2
Jack 8 3 5
Jill 5 4 9
Mike 6 7 3
Ctrl-Z
Joe 3 5 2 3.33
Tim 4 1 5 3.33
Jane 6 3 2 3.67
Jack 8 3 5 5.33
I'm basically needing a program to read input with names, and three numbers. The output should print the names and numbers I inputted and then the average of each set of numbers. I'm able to create a class file, but after I press Ctrl+z, the program doesn't output anything.
public class Average {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
String [] names = new String [n];
double [] a = new double [n];
double [] b = new double [n];
double [] c = new double [n];
int counter = 0;
while (counter < n) {
String [] run = StdIn.readAllStrings();
double [] value = StdIn.readAllDoubles();
counter++;
}
int i = 0;
double sum = 0.0;
while (!StdIn.isEmpty()) {
double value = StdIn.readDouble();
sum += value;
n++;
double average = sum / n;
StdOut.print(names);
StdOut.print(value);
StdOut.printf("%.2f", average);
}
}
}
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(Pattern.compile("\n"));
scanner.forEachRemaining(s -> {
if(s.replace(" ","").equals(""))return;
System.out.println(s+" "+Arrays.stream(s.split(" ")).skip(1).mapToInt(Integer::parseInt).average().orElse(0));
});

I am getting an ArithmeticException Error for dividing by zero. But I am not. Why?

Here is the coding question for which I am trying to solve
Write a program that reads two numbers aa and bb from the keyboard and calculates and outputs to the console the arithmetic average of all numbers from the interval [a; b][a;b], which are divisible by 33.
Sample Input 1:
-5
12
Sample Output 1:
4.5
Here is my Code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double average = 0;
int a = scanner.nextInt();
int b = scanner.nextInt();
Problem: Throws Arithmetic Exception
What is the problem?
Your variable i loops from -5 to 12. Then, you divide (a + b) / i (line 14).
0 is between -5 and 12. Thus, you will eventually divide by zero.
(I assume that line 13 is supposed to prevent this, but the way you have written it, it does not. In fact, 0 is among the very few values of i for which line 14 will actually be executed.)
According to your sample input and sample output, you need to add all the numbers in the range that are divisible by 3 and divide that total by how many different numbers are in the range.
Between -5 and 12, the numbers that are divisible by 3 are:
-3, 0, 3, 6, 9, 12
When you add them all together, you get 27.
And there are 6 different numbers altogether.
So the average is 27 divided by 6 which gives 4.5
Now for the code.
import java.util.Scanner;
public class RangeAvg {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter lower bound: ");
int a = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter upper bound: ");
int b = scanner.nextInt();
int lower = Math.min(a, b);
int upper = Math.max(a, b);
int total = 0;
int count = 0;
for (int i = lower; i <= upper; i++) {
if (i % 3 == 0) {
System.out.println(i);
total += i;
count++;
}
}
System.out.println("total = " + total);
System.out.println("count = " + count);
if (count > 0) {
double average = (double) total / count;
System.out.println("average = " + average);
}
else {
System.out.printf("No numbers divisible by 3 between %d and %d%n", lower, upper);
}
}
}
Below is a sample run:
Enter lower bound: -5
Enter upper bound: 12
-3
0
3
6
9
12
total = 27
count = 6
average = 4.5

Java print multiple lines after reading multiple lines

(It's my homework task. So I can't make any changes to the task like changing the rules of input.)
I need to calculate
a^m mod n
and print out the result. (I've already figured out how to code the calculation.)
But the question said there'll be multiple lines of input:
IN:
12 5 47
2 4 89
29 5 54
and need to print all the results together after reading all the lines of input. (You can't print the results right after one line of input.)
OUT:
14
16
5
The code I've tried so far:
import java.util.Scanner;
public class mod {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int count = 0;
while (input.hasNextLine()){
count++;
}
int[] array = new int[count];
for (int i = 0; i < count; i ++){
int a = input.nextInt();
int m = input.nextInt();
int n = input.nextInt();
int result = (int)((Math.pow(a, m)) % n);
array[i] = result;
}
for (int x : array){
System.out.println(x);
}
}
}
I tried to count the lines of input and build an array of that size to store the results.
But it seems my code fail to detect the end of input and keep looping.
You can store the user's input in the initial loop with a List<String>, I would suggest terminating the loop on an empty String and only adding lines that match the three numbers separated by whitespace characters. Also, I would print the result in the second loop. Then you don't need a result array. I would also prefer formatted io (i.e. System.out.printf). Like,
Scanner input = new Scanner(System.in);
List<String> lines = new ArrayList<>();
while (input.hasNextLine()) {
String line = input.nextLine();
if (line.isEmpty()) {
break;
} else if (line.matches("\\d+\\s+\\d+\\s+\\d+")) {
lines.add(line);
}
}
int count = lines.size();
for (int i = 0; i < count; i++) {
String[] tokens = lines.get(i).split("\\s+");
int a = Integer.parseInt(tokens[0]), m = Integer.parseInt(tokens[1]),
n = Integer.parseInt(tokens[2]);
int result = (int) ((Math.pow(a, m)) % n);
System.out.printf("(%d ^ %d) %% %d = %d%n", a, m, n, result);
}
I tested with your provided input,
12 5 47
2 4 89
29 5 54
(12 ^ 5) % 47 = 14
(2 ^ 4) % 89 = 16
(29 ^ 5) % 54 = 5

My logical program is not giving the correct output?

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

Categories