I'm trying to write a program that prints the results of the exponents of the number 2 and I want to print it out 10 times. I want to create a a method that calculates the value of the exponents using the Math.pow(x,y) method.
2 to the power of 0 = 1
2 to the power of 1 = 2
2 to the power of 2 = 4
I have a couple of questions. Can you use the Math.pow method in a for loop like I did below? How do you declare the value of x and y in the method Math.pow(x, y) inside a for loop or do you have to do it outside a for loop? Also, in the raiseIntPower method in Eclipse when I use int n as a parameter it gives me a "duplicate local variable error." My understanding is the method parameters specifies the argument the method requires. I don't understand the meaning of that duplicate error.
import acm.program.*;
public class Exponents extends ConsoleProgram {
public void run(){
for (int n = 0; n <= 10; n++) {
println("2 to the power of " + n + " = " + raiseIntPower(n));
}
}
private int raiseIntPower (int n){
int total = 0;
for( int n = 0; n <= 10; n++){
total = Math.pow(2, n);
}
return total;
}
}
I dont understand what are you trying to do
just replace the statement
println("2 to the power of " + n + " = " + raiseIntPower(n));
with
println("2 to the power of " + n + " = " + Math.pow(2,n));
and it should do it , no need for raiseIntPower()
I think you are confused about the usage of Math.pow() , please refer here for clarifications Math.pow()
Math#pow(double a, double b) where a is the base and b is the exponent, ab and it returns double so if you want to discard precision then you have to format return value.
you can remove raiseIntPower method.
for (int n = 0; n <= 10; n++) {
println("2 to the power of " + n + " = " + Math.pow(2,n));
}
check this one
import acm.program.*;
public class Exponents extends ConsoleProgram {
public void run(){
for (int n = 0; n <= 10; n++) {
println("2 to the power of " + n + " = " + raiseIntPower(n));
}
}
private int raiseIntPower (int n){
int total = 0;
total = (int)Math.pow(2, n);
return total;
}
}
Eclipse gives you a "duplicate local variable error" because there is a duplicate variable.
private int raiseIntPower (int n){
int total = 0;
for( int n = 0; n <= 10; n++){
total = Math.pow(2, n);
}
return total;
}
You declared a variable n for input. In the for loop, you declared another variable n. The int n and references to it in the for loop should be changed to another name, such as int i.
Related
Write a method called AddUp100 which takes in one value (an integer) and returns the sum of the next 100 numbers (int) on completion of the method. It does not consider the starting number, just the next 100 numbers. The method will return an int.
The method accepts any integer (positive or negative) which in the int range and prints out the addition of the next 100 numbers. It then returns the answer as an integer
Note: it only prints out the sum of the numbers.
So if 12 was entered, the program would print out
i.e. the program would add up 13+14+15+...+ 112. = 6250
This is my try:
private static int AddUp100(int input) {
input = input + 1;
int sum = input;
for (int i = 0; i < 10; i++ ) {
sum = sum + i;
System.out.println("Sum in loop is: " + sum);
}
System.out.println("Sum is: " + sum);
return input;
}
}
Second edit - It shows the correct adding up of numbers, however how do i tell the program to add only the next 100 numbers not more ?
private static int AddUp100(int input) {
int sum = 0;
input = input + 1;
System.out.println("input before loop " + input);
for (int i = input ; i < 100; i++) {
sum = sum + i;
System.out.println("Sum: " + sum);
}
return sum;
}
This can simplified to
long sum = 0;
long input = 12;
for (int loop = input + 1; loop <= input + 100; loop++ )
sum += loop;
System.out.println(sum);
output
6250
As you can start with any int value, then it would be better to store the sum and input in a long value to prevent Integer overflow i.e. Integer.MAX_VALUE + 1
Just write a for loop that runs 100 times. Within the loop, add the current input to the sum and increment the input by 1.
private static int AddUp100(int input) {
int sum = 0;
input = input + 1;
System.out.println("input before loop " + input);
for (int i = 0 ; i < 100; i++) {
sum += input;
input += 1
System.out.println("Sum: " + sum);
}
return sum;
}
I am having trouble to add a set of integers in a sequence. I have three variable: start, number, and end.
If I "start" at 5, then add all the integers up to "number" ( for example 9) , then decrement from 9 to the integer "end" (in this case to -1): (5,9,-1) => 5+6+7+8+9+8+7+6+5+4+3+2+1+0+ - 1 , which then i would print the result: total = 70. how can i accomplish this?
public class SequenceNumbers {
public static void main(String[] args) {
int start = 5;
int num = 9;
int end = -1;
int sum = 0;
for(int i = start; i <= num; i++)
{
// sum = sum + i;
sum += i;
}
int total = 0;
for ( int n = num; n != end; n--) {
total = (sum + (num - 1));
}
System.out.println("Result = " + total);
}
}
In the second loop, you overwrite total in each iteration. I'd keep the same pattern you had in the first loop, and just keep adding to sum. Note that it should start with num - 1, though, so you don't count that number twice:
int sum = 0;
for(int i = start; i <= num; i++) {
sum += i;
}
for ( int i = num - 1; i >= end; i--) {
sum += i;
}
System.out.println("Result = " + sum);
I guess you need this for an exercise?
But if you need a one-liner, this is a possible solution:
import java.util.*;
import java.util.stream.*;
public class MyClass {
public static void main(String args[]) {
;
int start = 5;
int num = 9;
int end = -1;
int total = Stream.concat(Stream.iterate(start, n -> n + 1).limit(num-start+1), Stream.iterate(num-1, n -> n - 1).limit(num-end)).mapToInt(Integer::intValue).sum();
System.out.println("Result = " + total);
}
}
You were almost there. All your code is fine until this one line in your second for loop:
total = (sum + (num - 1));
This line says "set total equal to sum plus one less than num". There's a problem there; sum and num are never changed by the for loop, so actually your for loop is doing nothing. You've set up your for loop nicely, though, and you gave yourself the variable n. All you need to do is keep adding to sum, and add n each time, like so:
sum += n;
Then in your println you can just use sum instead of total, like so:
System.out.println("Result = " + sum);
On second iteration for the total result you should decrement from max number which is 9 to min number which is -1. That means greater or equal to lowest value. ; >= ; -- .
The != comparison operator is to compare two values and the result is always a boolean type.
I need to write up factorial up to 23! I can do factorial up to 20! but after that I am lost because the number gets too big. I cannot use BigInteger.
I have to store the 0s from the rightmost digit so example outputs:
10! = 3628800 --> fac=36288, num10 = 2
23! = 2585..976640000 --> fac= 2585..97664, num10 = 4
import java.util.Scanner;
public class Factorial10{
public static void main(String[] args){
long fac; // long: factorial is very large
long pre_fac; // to check overflow
int i, n;
int num10;
Scanner sc = new Scanner(System.in);
System.out.print("n? ");
n = sc.nextInt();
// Start from fac = 0! = 1
for(i= 1, fac= 1L; i<n; i++){
pre_fac = fac;
fac *= i;
// check if overflowed
if(pre_fac != fac /i){
System.out.println("Overflowed at " + i + "! = " + fac);
fac = pre_fac; // roll back to the previous, unoverflowed
break;
}
}
System.out.println((i-1) + "! = " + fac + "(fac = , num10 = )");
}
}
```
Most miss a crucial part of your question:
I have to store the 0s from the rightmost digit
10 has the factors 2 and 5, so you only need to store how often each number between 1 and 23 can be divided by 2 and 5.
For example, with 10:
i 1 2 3 4 5 6 7 8 9 10 SUM
div2 0 1 0 2 0 1 0 3 0 1 8
div5 0 0 0 0 1 0 0 0 0 1 2
As we can see, the minimum of both sums is 2, so 10! should end with 00.
Indeed, 10! is 3628800.
The math behind this is 10! = x * 2^8 * 5^2, for some x that can't be divided by 2 or 5.
An other observation is that the number of 5s increases much slower, so we can skip counting the 2s.
With this knowledge, we can calculate the number of ending 0s by checking how often each number divides 5:
private static int numZerosInFactorial(int n) {
int divBy5 = 0;
for (int i = 1; i <= n; i++) {
for (int j = i; (j % 5) == 0; j /= 5) {
divBy5++;
}
}
return divBy5;
}
(There are are a few small improvements you can do to the above method)
The other question now is: Do you really need the value of n!?
And if yes, with what precision? Is it fine to calculate n! with double now?
Thanks to a comment from Michael, I noticed that we can in fact calculate the factorial without the zeros and then use string concatenation to display the result.
When calculating the factorial without zeroes, we have to basically do the opposite of what we did in numZerosInFactorial, so instead of multiplying with a multiple of 5, we divide by 2:
private static long factorialWithoutZeroes(int n) {
long result = 1;
for (int i = 1; i <= n; i++) {
long div = 1;
int j;
for (j = i; (j % 5) == 0; j /= 5) {
div *= 2;
}
result = result / div * j;
}
return result;
}
The final result would be:
// We have already read n from stdin
long fac = factorialWithoutZeroes(n);
int num10 = numZerosInFactorial(n);
System.out.println(n + "! = " + (fac + "0".repeat(num10)) + " (fac = " + fac + " , num10 = " + num10 + ")");
Indeed, this approach works up to n == 23. And the output format is a good hint that this is the expected approach.
Have you try to use double instead of long. As documentation in Double.Max - it can hold up to 1.7976931348623157e+308
Just implement your own kind of big integer:
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int[] factorial = factorial(n);
for (int i = factorial.length - 1; i >= 0; i--) {
System.out.print(factorial[i]);
}
}
static int[] factorial(int n) {
int[] factorial = { 1 };
for (int i = 1; i <= n; i++) {
factorial = multiply(factorial, i);
}
return factorial;
}
static int[] multiply(int[] multiplicand, int multiplicator) {
int carry = 0;
for (int j = 0; j < multiplicand.length; j++) {
multiplicand[j] = multiplicand[j] * multiplicator + carry;
carry = multiplicand[j] / 10;
multiplicand[j] %= 10;
}
while (carry > 0) {
multiplicand= Arrays.copyOf(multiplicand, multiplicand.length + 1);
multiplicand[multiplicand.length - 1] = carry % 10;
carry /= 10;
}
return multiplicand;
}
}
Try it online!
If you can't use BigInteger, then you could try implementing your own big number library:
How to handle very large numbers in Java without using java.math.BigInteger
You can use the class BigDecimal of java.lang.math
But that can take all your memory.
Is there any replacement of long double in java?
I want to create a program to find the sum of factorial of all numbers in a series till 20.
I have to find 's' in s = 1 + (1*2) + (1*2*3) + ...(1*2*3...20).
I tried a program but it is not working. I am using BlueJ IDE.
int a =1;
int s = 0;
for(int i = 1; i <= 10; i++)
{
while (i >0)
{
a = a * i;
i--;
}
s = s+a;
}
System.out.println(s);
The compiler does not show any error message but when I run the program the JVM(Java Virtual Machine) keeps loading and the output screen does not show up.
You can try this one :
public class Main
{
public static void main (String[]args)
{
int fact = 1;
int sum = 0;
int i, j = 1;
for (i = 1; i <= 20; i++)
{
for (j = 1; j <= i; j++)
{
fact = fact * j;
}
sum += fact;
System.out.println ("sum = " + sum);
fact = 1;
}
}
}
Always give proper variable name and Try to avoid to use same variable at different places i.e you have use variable i in outer and inner loop which is not good habit.
You should be using a different loop variable name in your inner loop, and you also need to use a long to store your sum. In fact, I would first write a method to multiply up to a number in the series. Like,
static long multiplyTo(int n) {
long r = 1L;
for (int i = 2; i <= n; i++) {
r *= i;
}
return r;
}
Then you can invoke that and calculate your sum with a simple loop. Like,
long sum = 0L;
for (int i = 1; i <= 20; i++) {
sum += multiplyTo(i);
}
System.out.println(sum);
I get
2561327494111820313
Using streams:
long s = LongStream.rangeClosed(1, 20)
.map(upper -> LongStream.rangeClosed(1, upper)
.reduce(1, (a, b) -> a * b))
.sum();
System.out.println(s);
Prints 2561327494111820313
I did the same program using Scanner Class
import java.util.*;
class Sum_Factorial
{
public static void main()
{
Scanner in = new Scanner(System.in);
int i; //Denotes Integer
int n; //Denotes Number
int f=1; //Denotes Factorial
int s=0; //Denotes Sum
System.out.println("Enter the value of N : ");
n=in.nextInt();
for(i=1; i<=n; i++)
{
f=f*i;
s=s+f;
}
System.out.println("Sum of the factorial numbers is "+s);
}
}
The question here would be to get the sum of powers (m^0 + m^1 + m^2 + m^3.... + m^n) using only FOR loops. Meaning, not using any other loops as well as Math.pow();
Is it even possible? So far, I am only able to work around getting m^n, but not the rest.
public static void main(String[] args){
Scanner scn = new Scanner(System.in);
int total = 1;
System.out.print("Enter value of m: ");
int m = scn.nextInt();
System.out.print("Enter value of n: ");
int n = scn.nextInt();
for (int i = 1; i <= n; i++){
total * m;
}
System.out.print(total);
}
Let's say m =8; and n = 4;
i gives me '1,2,3,4' which is what I need, but I am unable to power m ^ i.
Would be nice if someone could guide me into how it could be done, can't seem to progress onwards as I have limited knowledge in Java.
Thanks in advance!
You might want to rewrite it like this :
m^0 + m^1 + m^2 + m^3.... + m^n = 1 + m * (1 + m * (1 + m * (.... ) ) )
And you do it in a single for loop.
This should do the job (see explanations in comments):
public long count(long m, int pow) {
long result = 1;
for(int i = 0;i<pow; i++) {
result*=m +1;
}
return result;
}
You can nest loops. Use one to compute the powers and another to sum them.
You can do below:
int mul = 1;
total = 1;
for(int i=1;i<=n;i++) {
mul *= m;
total += mul;
}
System.out.println(total);
You can use a single loop which is O(N) instead of nested loops which is O(N^2)
long total = 1, power = m
for (int i = 1; i <= n; i++){
total += power;
power *= m;
}
System.out.print(total);
You can also use the formula for geometric series:
Sum[i = k..k+n](a^i) = (a^k - a^(k+n+1)) / (1 - a)
= a^k * (1 - a^(n+1)) / (1 - a)
With this, the implementation can be done in a single for loop (or 2 simple for loop): either with O(n) simple looping, or with O(log n) exponentiation by squaring.
However, the drawback is that the data type must be able to hold at least (1 - a^(n+1)), while summing up normally only requires the result to fit in the data type.
This is the solution :
for(int i=0;i<n;i++){
temp=1;
for(int j=0;j<=i;j++){
temp *= m;
}
total += temp;
}
System.out.println(total+1);
You can easily calculate powers using your own pow function, something like:
private static long power(int a, int b) {
if (b < 0) {
throw new UnsupportedOperationException("Negative powers not supported.");
}
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
return a * power(a, b - 1);
}
Then simply loop over all the values and add them up:
long out = 0;
for (int i = 0; i <= n; ++i) {
out += power(m, i);
}
System.out.println(out);
I would add that this is a classic dynamic programming problem as m^n is m * m^(n-1). I would therefore add caching of previously calculated powers so that you don't have to recalculate.
private static Map<Integer, Long> powers;
public static void main(String args[]) {
int m = 4;
int n = 4;
powers = new HashMap<>();
long out = 0;
for (int i = 0; i <= n; ++i) {
out += power(m, i);
}
System.out.println(out);
System.out.println(powers);
}
private static long power(int a, int b) {
if (b < 0) {
throw new UnsupportedOperationException("Negative powers not supported.");
}
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
Long power = powers.get(b);
if (power == null) {
power = a * power(a, b - 1);
powers.put(b, power);
}
return power;
}
This caches calculated values so that you only calculate the next multiple each time.