I am new to Java and stackoverflow. I am writing a program that can add power in Java, for example: 2^1, 2^1+2^2, 2^1+2^2+2^3,.. so on.
I have written below program and I don't know what I am doing wrong when I am trying to add the powers. I just get 2^1 2^2 2^3,... as output. I hope you get the idea from my code and it will be a great help if you guys can help me learn.
Thank you in advance!
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a: ");
int a = sc.nextInt(); //a = first number
System.out.print("Enter b: ");
int b = sc.nextInt(); //b = second number
System.out.print("Enter t: ");
int t = sc.nextInt(); //t = no. of iterations
int x=0, sum = 0;
for (int i = 0; i < t;) {
for (int j = 0; j < t; j++) {
int pow = (int) Math.pow(2, i);
x = a + (pow * b);
i++;
System.out.printf("%d ", x);
sum = x;
}
sum = x + sum;
System.out.println(sum);
}
}
According to Mathematics rules, if it is addition among the numbers, for example 2^1 + 2^2 + 2^3 + 2^4... Then it is simple you don't need two loops and the t variable. You just need the base and the last exponent limit.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the base: ");
int a = sc.nextInt(); //a = first number
System.out.print("Enter iterations: ");
int b = sc.nextInt(); //b = No of iterations
int sum = 0;
for (int i = 1; i <= b; i++) {
sum += Math.pow(a, i);
}
System.out.println("The sum is " + sum);
}
But if there is multiplication among the numbers, then you will add the exponents if the base is same. Fox example 2^1 * 2^2 * 2^3 * 2^4.... Then you may do it as below.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the base: ");
int a = sc.nextInt(); //a = first number
System.out.print("Enter iterations: ");
int b = sc.nextInt(); //b = No of iterations
Double res;
int powerSum = 0;
for (int i = 1; i <= b; i++) {
powerSum += i;
}
System.out.println("Power sum is " + powerSum);
res = Math.pow(a, powerSum);
System.out.println("The result is " + res);
}
In your inner loop
int pow = (int) Math.pow(2, i);
shouldn't you be using j instead of i?
Very simply you can do it as below:
public static int getPow(int num, int pow) {
if (pow < 2) {
return num;
}
return (int) Math.pow(num, pow) + getPow(num, --pow);
}
Usage:
int pow = getPow(2, 4);// 2*1 + 2*2 + 2*2*2 + 2*2*2*2 = 2+4+8+16 = 30
System.out.println("pow = " + pow);
And Result:
pow = 30
Related
I have an exercise about raising certain numbers to a given power.
The exact one I have problems with:
We use the integers a, b, and n to create the following series:
(a + 2^0 * b), (a + 2^0 * b + 2^1 * b), ... ,(a + 2^0 * b + 2^1 * b + ... + 2^n-1 * b)
You are given q queries in the form of a, b, and n. For each query, print the series corresponding to the given a, b, and n values as a single line of n space-separated integers.
Input Format
The first line contains an integer, q, denoting the number of queries. Each line i of the q subsequent lines contains three space-separated integers describing the respective ai, bi, and ni values for that query.
Output Format
For each query, print the corresponding series on a new line. Each series must be printed in order as a single line of n space-separated integers.
I tried this code:
import java.util.*;
import java.lang.Math.*;
class Playground {
public static void main(String[ ] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
for(int i = 0; i < q; i++) {
int a = in.nextInt();
int b = in.nextInt();
int n = in.nextInt();
int num = a;
for(int j = 0; j < n; j++) {
num += (((int) Math.pow(2, j)) * b);
System.out.print(num + " ");
}
System.out.println();
}
}
}
But it failed the test, even though the "Expected output" and the actual output looked the same. I tried searching for other solutions, but the ones I found were not that different from my own.
Input
2
0 2 10
5 3 5
Expected Output
2 6 14 30 62 126 254 510 1022 2046
8 14 26 50 98
Output
2 6 14 30 62 126 254 510 1022 2046
8 14 26 50 98
This is almost certainly related to the trailing space in your output:
2 6 14 30 62 126 254 510 1022 2046 | <<= Trailing space
8 14 26 50 98 | <<= Trailing space
Fix your output as follows:
for(int j = 0; j < n; j++) {
if (j != 0) {
System.out.print" ");
}
num += (((int) Math.pow(2, j)) * b);
System.out.print(num);
}
Note that you can avoid calling Math.pow at all, because powers of 2 can be computed using bit shift expression 1 << j; multiplication of b by 1 << j is equivalent to shifting b left by j:
for(int j = 0; j < n; j++) {
if (j != 0) {
System.out.print" ");
}
num += (b << j);
System.out.print(num);
}
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int TestCase = sc.nextInt();
while (TestCase-- > 0) {
int a = 0, b = 0, n = 0;
a = sc.nextInt();
b = sc.nextInt();
n = sc.nextInt();
int sum = a + b;
for (int i = 1; i < n;) {
System.out.print(sum + " ");
sum += ((int) Math.pow(2, i) * b);
i++;
if (i == n) {
System.out.print(sum);
}
}
System.out.println();
}
sc.close();
}
}
public static void main(String []argh){
Scanner in = new Scanner(System.in);
int t=in.nextInt();
for(int i=0;i<t;i++){
int a = in.nextInt();
int b = in.nextInt();
int n = in.nextInt();
int power = 1,sum=0;
for(int j=0;j < n;j++)
{
sum=a+(power*b);
System.out.print(sum+" ");
power = power * 2;
power++;
}
System.out.println("");
}
in.close();
}
//where 2^0*b, 2^0*b + 2^1*b, 2^0*b + 2^1*b + 2^2*b .....,2^(k+1) - 1
import java.util.*;
import java.io.*;
import java.lang.Math;
class Solution{
public static void main(String []argh){
Scanner in = new Scanner(System.in);
int t=in.nextInt();
for(int i=0;i<t;i++){
int a = in.nextInt();
int b = in.nextInt();
int n = in.nextInt();
int count = 0;
for(int j=0;j<n;j++) {
System.out.print((int)(a+b*(Math.pow(2,j + 1)-1))+" ");
}
System.out.println();
}
in.close();
}
}
for (int j = 0; j < n; j++ ){
if(j==0){
output = output + (a + (int)Math.pow(2,j) * b);
}
else{
output = output + ((int)Math.pow(2,j) * b);
}
System.out.print(output+" ");
}
System.out.println();
Please check the following simple method to solve this problem but mind it, you can decrease time complexity using recursion, here I am going without recursion:
import java.util.*;
import java.io.*;
import java.lang.Math;
class Solution{
public static void main(String []argh){
Scanner in = new Scanner(System.in);
int t=in.nextInt();
for(int i=0;i<t;i++){
int a = in.nextInt();
int b = in.nextInt();
int n = in.nextInt();
double sum=0;
for(int j=1;j<=n;j++)
{
sum=a;
for(int k=0;k<j;k++)
{
sum=sum+(b*Math.pow(2, k));
}
System.out.print((int)sum+" ");
}
System.out.println();
}
in.close();
}
}
import java.util.*;
import java.io.*;
class Solution{
public static void main(String []argh){
Scanner in = new Scanner(System.in);
int t=in.nextInt();
int a =0,b=0,n=0;
for(int i=0;i<t;i++){
a = in.nextInt();
b = in.nextInt();
n = in.nextInt();
arrange(a,b,n);
}
in.close();
}
public static void arrange(int a,int b,int n){
int sum = a+b;
for(int j=1; j<=n; j++){
System.out.print(sum+" ");
sum+=((Math.pow(2,j))*b);
}
System.out.println();
}
}
Here's the full code with more optimized and cleaned - It will run all your test cases
import java.util.*;
import java.io.*;
class Solution
{
public static void main(String []argh)
{
Scanner in = new Scanner(System.in);
int t=in.nextInt();
for(int i=0;i<t;i++)
{
int a = in.nextInt();
int b = in.nextInt();
int n = in.nextInt();
int s=0;
s=s+a;
for(int j=0;j<n;j++)
{
s+=(Math.pow(2,j))*b;
System.out.print(s+" ");
}
System.out.println();
}
in.close();
}
}
import java.util.*;
import java.io.*;
class Solution{
public static void main(String []argh){
Scanner in = new Scanner(System.in);
int t=in.nextInt();
for(int i=0;i<t;i++){
int result = 0;
int a = in.nextInt();
int b = in.nextInt();
int n = in.nextInt();
for (int j = 0; j < n; j++ ){
if(j==0){
result = result + (a + (int)Math.pow(2,j) * b);// for (a + 2^0 * b)
}
else{
result = result + ((int)Math.pow(2,j) * b); // for (a + 2^0 * b + 2^1 * b)
}
System.out.print(result+" ");
}
System.out.println();
}
in.close();
}
}
Try this completed code...
import java.util.*;
import java.io.*;
class Solution{
public static void main(String []argh){
Scanner in = new Scanner(System.in);
int t=in.nextInt();
for(int i=0;i<t;i++){
int a = in.nextInt();
int b = in.nextInt();
int n = in.nextInt();
for(int x=0; x<n; x++){
a+=(Math.pow(2,x)*b);
System.out.print(a+" ");
}
System.out.println();
}
in.close();
}
}
I am a beginner trying to program a java code to produce output numbers that is a prime factor of two and five.
For example, if input is 8, then output should be 2 4 5 8.
However, whenever I print my output, the result will be 2 5 4 5 8 5.
Please advice on where I have gone wrong.
Thank you
import java.util.Scanner;
class twofive {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter n:");
int n = sc.nextInt();
double num = 0;
double num2 = 0;
for (int i = 1; (((Math.pow(2,i))<= n) || ((Math.pow(5,i)) <=n) || (((Math.pow(2,i))<= n) && ((Math.pow(5,i)) <=n))) ; i++) {
if (( Math.pow(2,i)) <= n)
num = (Math.pow(2,i));
int convert = (int) num;{
System.out.print(convert + " ");
}
if ((Math.pow(5,i)) <= n)
num2 = (Math.pow(5,i));
int convert2 = (int) num2;
{System.out.print(convert2 + " ");
}
}
}
}
After you review #AmedeeVanGasse 's comment, you need to fix your braces.
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter n:");
int n = sc.nextInt();
double num = 0;
double num2 = 0;
for (int i = 1; Math.pow(2,i))<= n) || ((Math.pow(5,i)) <=n) || (((Math.pow(2,i))<= n) && ((Math.pow(5,i)) <=n))) ; i++) {
if (( Math.pow(2,i)) <= n) {
num = (Math.pow(2,i));
int convert = (int) num;
System.out.print(convert + " ");
}
if ((Math.pow(5,i)) <= n) {
num2 = (Math.pow(5,i));
int convert2 = (int) num2;
System.out.print(convert2 + " ");
}
}
}
You should also review the logic in your for loop and if statements. They are full of unneeded redundancies.
I need to calculate the sum of 2^0+2^1+2^2+...+2^n, where n is a number entered by the user. The main problem is that I don't know how to use the while loop to sum the different result of 2^n up.
Here is what I've tried:
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
while(power <= i) {
Math.pow(number, i);
sum = sum + Math.pow(number, i);
i = i + 1;
}
int result = (int)Math.pow(number, i);
System.out.println("The sum is: " + result);
}
}
Only you have to do is:
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
double sum = Math.pow(2,power+ 1 ) - 1;
System.out.println("The sum is: " + sum);
}
}
In this link explains the math expresion
All fine, just a few changes.
Change the parts code to
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
/*Remove this --------> while(power <= i) {*/
while (i <= power) {//it should be this
/*Remove this -------> Math.pow(number, i);*/
sum = sum + Math.pow(number, i);
i = i + 1;
}
System.out.println("The sum is: " + sum);
Your conditional is backwards, it should read:
while (i <= power)
You compute the sum of powers, then completely ignore it, just printing out the result of 2^i. you should be printing out sum, something like:
while (i <= power) {
sum += Math.pow(number, i);
i++;
}
System.out.println("The sum is: " + sum);
For style points this won't handle a negative power, so you'll need to test for that.
Dont understand why do you want to loop in this case. You can do it like :
System.out.println("The sum is: "+(Math.pow(2, power+1)-1 ));
But if you really want to use loop try this :
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
while(i<=power) {
sum = sum + Math.pow(number, i);
i = i + 1;
}
int result = (int)Math.pow(number, i);
System.out.println("The sum is: " + sum);
Here is a solution with comments to explain the logic. While loops need some kind of variable to control the number of iterations. That variable of course needs to be updated somewhere inside the loop.
You can compute the sum of the powers with the Math.pow() function, obviously. No import statement is needed to use it. I hope this helps. Good luck.
/* Scanner and variable to get and hold user input */
Scanner scan = new Scanner( System.in );
int userInput = 0;
/* Variable to hold the sum, initialized to 0.0 */
double sum = 0.0;
/* Prompt the user, and obtain the reply */
System.out.print( "Enter the exponent: ");
userInput = scan.nextInt();
/* The while loop and it's initialized counter */
int counter = 0;
while( counter <= userInput ){
/* Add each power to sum using Math.pow() */
sum = sum + Math.pow( 2, counter );
/* Watch the output as the loop runs */
System.out.println( "Sum: " + sum );
counter++; // Increment counter, so the loop exits properly
} // End while loop
public class SumofSquare {
public static void main(String[] args) {
// TODO Auto-generated method stub
String c = "123";
char d[] = c.toCharArray();
int a[] = new int[d.length + 1];
for (int i = 0; i < d.length; i++)
a[i] = d[i] - 48;
int r = 0;
for (int i = 0; i < c.length(); i++)
r = r + (int) Math.pow(a[i], a[i + 1]);
System.out.println(r);
}
}
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
int power=Integer.parseInt(reader.nextLine());
int number=2;
int i=0;
int result=0;
while (power>=i) {
result += (int)Math.pow(number, i);
i++;
}
System.out.println("The result is "+result);
}
}
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
double power=Double.parseDouble(reader.nextLine());
int number=2;
int i=0;
double sum=0;
while (power>=i) {
sum=sum+Math.pow(number, i);
i++;
}
System.out.println("The sum is "+sum);
}
I am working on an assignment which prompts the user to input an integer, and displays that integer with the digits separated by spaces, and provides the sum of those digits. I have this working, but my individual digit display is form the last digit to the first. How can I make it display the digits from first to last?
Here is what I have so far:
import java.util.*;
public class SeparateAndSum{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int num, temp, sum;
System.out.print("Enter a positive interger: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
do
{
temp = num % 10;
sum = sum + num % 10;
num = num / 10;
System.out.print(" " + temp + " ");
}while (num > 0);
System.out.println("The sum of the digits = " + sum);
}
}
One option would be to use the String#valueOf(Integer) method.
Example
int input = 12345;
String inputStr = String.valueOf(input);
for(char c : inputStr.toCharArray()) {
// Print out each letter.
}
if you use the method String.valueOf(12345)
you can easily reverse the String with the method in this library:
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#reverse(java.lang.String)
StringUtils.reverse(String.valueOf(input));
Here is the solution
import java.util.*;
public class SeparateAndSum{
static Scanner console = new Scanner(System.in);
int num, temp, sum;
System.out.print("Enter a positive interger: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
ArrayList<Integer> values = new ArrayList<>();
do
{
temp = num % 10;
sum = sum + num % 10;
num = num / 10;
values.add(temp);
}while (num > 0);
Collections.reverse(values);
Iterator<Integer> it = values.iterator();
while(it.hasNext()){
System.out.println(" "+it.next()+" ");
}
System.out.println("The sum of the digits = " + sum);
}
}
BTW you should have to import ArrayList etc.
I would highly recommend putting the number into a String and then reading it, parsing it, and use the number however you want. As follows,
int input = 12345;
String inputString = input + "";
int sum = 0;
for (int i = 0; i < inputString.length(); i++) {
sum += Integer.parseInt(inputString.charAt(i) + "");
}
System.out.println(sum);
However an alternative way, not as pretty is..
int input = 12345;
int sum = 0;
while (input > 0) {
int i = (input + "").length() - 1;
int n = (int) (input / Math.pow(10, i));
input -= (int) (n * Math.pow(10, i));
sum += n;
}
System.out.println(sum);
import java.io.*;
public class TestCaseAbcd {
public static void main(String args[]) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(
float x0;
float a, c, mod;
int num, ch = 0;
double[] rNumbers;
double[] rTemp;
System.out.println("Enter the SEED value: ");
System.out.println("x0 ");
x0 = Float.parseFloat(stdin.readLine());
System.out.println("Enter the multiplier's value:");
System.out.println("a: ");
a = Float.parseFloat(stdin.readLine());
System.out.println("Enter the value of increment c and modulus m: ");
System.out.println("c: ");
c = Float.parseFloat(stdin.readLine());
System.out.println("m: ");
mod = Integer.parseInt(stdin.readLine());
System.out.println("How many random nunbers u need? ");
num = Integer.parseInt(stdin.readLine());
rNUmbers = new double[num];
rTemp = new double[rNumbers.length];
rTemp[0] = x0;
for (int i = 0; i < num; i++)
{
if(i + 1 != num)
{
rTemp[i + 1] = (((rTemp[i] * a) + c) % mod);
}
else
{
break;
}
}
for (int i = 0; i < rNumbers.length; i++)
{
if (i + 1 != num)
{
rNumbers[i] = rTemp[i] / mod;
}
else
{
break;
}
}
System.out.println("The PSEUDO random numbers are: ");
for (int i = 0; i < rNumbers.length; i++)
{
System.out.println(rNumbers[i]);
}
double firstNum = rNumbers[0];
System.out.println("1. Select Mutant 1 ");
System.out.println("2. Select Mutant 2 ");
System.out.println("3. Exit ");
}
}
In the above code, the expected output should start from: 0.68.
But, instead it started from:
0.37.
In fact, even after I changed the following code:
rTemp[i+1] = ( ( (rTemp[i]*a) + c ) % mod);
to:
rTemp[i+1] = ( ( (rTemp[i]/a) + c ) % mod);
The output still started from 0.37.
The input values are:
x0 = 37
a = 7
c = 9
m = 100
Please help me in analyzing the code so as that the output shouldn't start with 0.37.
Summary of the problem: the code is producing the same number i.e. 0.37 no matter what the equation stated above in the code is modified to.
You're setting the first value in rTemp to 37, then you start printing from the first value. It only makes sense that the first value printed would be 0.37.
x0 = 37
mod = 100
...
rTemp[0] = x0;
...
rNumbers[i] = rTemp[i] / mod;
...
System.out.println(rNumbers[i]);
To achieve the output you're looking for, change this:
rTemp[0] = x0;
for (int i = 0; i < num; i++)
{
if(i + 1 != num)
{
rTemp[i + 1] = (((rTemp[i] * a) + c) % mod);
}
else
{
break;
}
}
to this:
rTemp[0] = (((x0 * a) + c) % mod);
for (int i = 0; i < num-1; i++)
{
rTemp[i + 1] = (((rTemp[i] * a) + c) % mod);
}
On a side note, if all you really want is an array of psudo-random doubles, it's easier to do something like this:
Random rnd = new Random(seed);
double[] rNumbers = new double[num];
for(int i = 0; i < num; i++)
rNumbers[i] = (double)rnd.nextInt(100) / 100;
For any given seed, you'll get the same array of doubles every time.