what is my error in the sum of power functions? - java

I was solving this problem6, I dont even know the answer but, when I finished I think that I will get Ok, but my answers fails, 7910956276398901303 this is my answer 1303, can you help me with this error, I dont understand what is wrong my logic , code??, Its just a simple power function
Corrected
this is the correct code
import java.math.BigDecimal;
public class Problema6 {
static BigDecimal sum = BigDecimal.valueOf(0);
static BigDecimal num = BigDecimal.valueOf(0);
public static void main(String args[]) {
int n = 2;
for (int i = 1; i <= 15; i++) {
sum = sum.add(power(i, n));
n++;
}
System.out.println(sum);
String number = sum.toString();
System.out.println(number.substring(number.length() - 4, number.length()));
}
public static BigDecimal power(int x, int y) {
num = BigDecimal.valueOf(x).pow(y).add(BigDecimal.valueOf(y).pow(x));
return num;
}
}

I think the problem is with using Math.pow(...). Switch to BigDecimal.pow(...) to avoid overflows

Related

How to use loops to find the exponent of a base that produces an argument

I am attempting to use loops to find the exponent of a given base that produces a specific argument. For example, in the equation 5^x=625, 5 would be the base and 625 would be the argument. I know that in that equation x=4 but I am unsure of how to get 4 in my return.
Here is what I have so far:
public static int log(int base, int argument) {
int result = 1;
for (int i=0; i<=; i++)
result = ;
return result;
}
I am unsure what to put for my condition statement and my result. What am I missing here?
edit: I forgot to mention that I am attempting to do this without using the math library. I also thought it might help to include my code for finding the powers:
public static int pow(int base, int exponent) {
int result = 1;
for(int i=0; i<exponent; i++) {
result = result*base;
}
return result;
I essentially just trying to reverse this to find the exponent.
Something like that:
public static int log(int base, int argument) {
if(argument <= 0 || base <= 0) {
throw new IllegalArgumentException("This method only works with positive integers");
}
int result = 1;
int i = 0;
while(result < argument) {
result = result * base;
i++;
}
if(result == argument) {
return i;
} else {
throw new IllegalArgumentException("There is no integer for x in base^x = argument");
}
}
This as some flaws as it handle all cases but it's a start.
This is more of a math question.
For the formula 5^x = 625, you find x using x = log₅(625) = log(625)/log(5).
So:
public static int log(int base, int argument) {
return (int) (Math.log(argument) / Math.log(base));
}
But maybe you already knew this, since you named the method right.
Count how many times you can divide the argument by the base while the result is 1 or greater:
public static int log(int base, int argument) {
int result;
for (result=0; argument>=1 ; result++) {
argument = argument/base;
}
return result;
}

Benford's Law Program in Java

I am making a program in Java to see if the Benford's Law is actually true. I am using BigDecimal, but there was an error ever since I implemented it.
import java.lang.*;
import java.math.BigDecimal;
public class BenfordLaw {
public static int oneornot(BigDecimal number) {
String str2num = number.toString();
if(str2num.startsWith("1")) {
return 1;
} else {
return 0;
}
}
public static void main(String[] args) {
int n = 0;
long sum = 0;
for (int i = 0; i < 10000; i++) {
BigDecimal number = BigDecimal.valueOf(Math.pow(2,n));
System.out.println(number);
double newnum = oneornot(number);
sum += newnum;
n+=1;
}
System.out.println(sum);
System.out.println(sum*0.0001);
}
}
If you run this program, there is an error.
The error is in the link below.
https://pastebin.com/ShJmGjdJ
Your program throws exception because of the following line:
BigDecimal number = BigDecimal.valueOf(Math.pow(2,n));
The variable n is incremented by 1 at every iteration up to 9999. Because of that Math.pow(2,n) is becoming so big, that at some point it exceeds the max value of double type. Eventually Double.toString (which is used by BigDecimal.valueOf) returns "Infinity" what leads to NumberFormatException.
Please replace the mentioned line with following to fix your problem:
BigDecimal number = BigDecimal.valueOf(2).pow(n));

How to use double for matrices

This is the code I wrote:
public class main
{
public static int arraySum(int[] arr)
{
int result = 0;
for(int i = 0; i < arr.length; i++)
{
result += arr[i];
}
return result;
}
public static int arraySumBetter(int[] a)
{
int result = 0;
for(int value : a)
{
result += value;
}
return result;
}
public static void main(String[] args)
{
int[] a = {1, 2, 3, 4, 48};
System.out.println(arraySum(a));
System.out.println(arraySumBetter(a));
}
}
When I run it, it prints:
58
58
But I want the result to be 58.0.
I changed all the int into double:
public class main
{
public static double arraySum(double[] arr)
{
double result = 0;
for(double i = 0; i < arr.length; i += 1)
{
result += arr[i];
}
return result;
}
public static int arraySumBetter(double[] a)
{
double result = 0;
for(double value : a)
{
result += value;
}
return result;
}
public static void main(String[] args)
{
double[] a = {1, 2, 3, 4, 48};
System.out.println(arraySum(a));
System.out.println(arraySumBetter(a));
}
}
But it didn't compile:
typed.java:8: error: incompatible types: possible lossy conversion from double to int
result += arr[i];
^
typed.java:19: error: incompatible types: possible lossy conversion from double to int
return result;
^
2 errors
Do I need to add more code? Or something else?
This is a slightly sneaky one: look at this code
for (double i = 0; i < arr.length; i += 1) {
result += arr[i];
}
the variable used for index of the array is a double all of a sudden, but an array index is always an integral value. That's what causes the compilation error.
Revert the index variable to int and you'll be all set. That is, revert your code to
for (int i = 0; i < arr.length; i += 1) {
result += arr[i];
}
Note: if all you want is just a result with one decimal, the solution you choose is pretty heavy handed, calculations on doubles are slower than those on integers, and double math has its own challenges - just look around here on SO. A simple way to keep all calculations in ints but at the same time print the result with 1 decimal could be
System.out.format("%.1f", (double) arraySumBetter(a));
in that case, you'd use the first version of arraySumBetter, ie public static int arraySumBetter(int [] a)
The problem is that an array can only be indexed using integers. This means, arr[true] or arr[5.32] is not allowed.
The compiler complains because it needs to convert the double to an integer value, and this would cut off the decimal places. Java never does that implicity - you have to cast it to an integer:
double foo = 5.32;
// convert to integer:
int bar = (int) foo;
In your case a typecast is not necessary. If the variable i is of type int, it works fine.
In the second method, you have the wrong return type. It returns a double, but the declaration says
public static int arraySumBetter
your problem in this function int arraySumBetter(double [] a)
return value is int but you declared result in your function as double variable so it will be a lossy conversion from double to int problem when you return result
it should be:
public static double arraySumBetter(double [] a)
also index counter type of array should be integer value :
for (int i = 0; i < arr.length; i += 1) // not double i
you can format your output in specific floating point precision using printf method:
System.out.printf("%.1f\n",arraySum(a));
System.out.printf("%.1f\n",arraySumBetter(a));

Using biginteger to find the sequence of sum of powers

Sum(N) =1^1+2^2+3^3+...+N^N
Using Java,
How would I use BigInteger to find the smallest integer N such that the value of Sum(N) is larger than 10^20?
I'm really stuck,please give me some advice
This is what I have so far:
import java.math.BigInteger;
public class PROJECTV1 {
public static void main(String [] args) {
BigInteger bResult= bigFunctionExample_2();
System.out.println(" => result_got:"+ bResult);
System.out.println(); //newline
}// end_main
public static BigInteger bigFunctionExample_2() {
BigInteger bSum = BigInteger.ZERO;
BigInteger bTmp;
String sSum;
// BigInteger bResult =0;
for (int i=1; ; i++) {
bTmp = BigInteger.valueOf(i);
bTmp = bTmp.pow(i); // i^i
bSum = bSum.add(bTmp); // sum = i^i+ (i-1)^(i-1)+ ....
sSum = bSum.toString();
if ( sSum.length() >21) {
System.out.println("i="+i +" bSum ="+bSum);
break;
}//
}//end_for
return bSum; // result
} // end_bigFunctionExample_2
}
Looking at your code, you have a line bTmp.pow(2). That squares the numbers in your series, but you need to raise bTmp to the bTmp power. Java doesn’t seem to want to take a BigInteger as an argument to pow, but you could replace pow with another for loop.
Also, sSum.length() >30 looks like it will only occur if your sum is greater than or equal to 1029. Is there a reason you convert the number to a string each time through the loop, rather than comparing the number to 1020? Perhaps you could put something like bSum > bMax as the test condition in your for loop, rather than leaving it blank and exiting with a break. Then you could make a new BigInteger bMax and set it to 1020 at the start of your code.
For testing, you could set bMax to something small, like 100, and see if your program gives the correct result. You can calculate the first few steps of the series by hand to check your program.
Here is a clue computing some factorials:
import java.math.*;
public class FactorialBig {
public static BigInteger factorial(BigInteger n) {
if (n.equals(BigInteger.ZERO))
return BigInteger.ONE;
else
return n.multiply(factorial(n.subtract(BigInteger.ONE)));
}
public static void main(String[] args) {
for (int n = 0; n < 20; n++) {
BigInteger f = factorial(new BigInteger(new Integer(n).toString()));
System.out.printf("factorial(%2d) = %20s%n", n, f.toString());
}
}
}
You know you should save the above as a file named "FacotrialBig.java".

Java - continues adding value on integer

im having a little problem about my codes
public class ex{
public static void main(String[] args) {
int sum,int a = 1,int b = 2;
int c = 1,int d = 2;
if (a<b) {
sum = sum+1;
}
if (c<b) {
sum = sum+1;
}
System.out.println("output :"+sum);
}
}
I wanted to add a value of 1 in the int sum if the conditions are met. but its not compiling
the output should be like this:
output: 2
First things first.. If you are a beginner to Java, this is an advise for you to learn well about the syntax of Java declaration, initialization and usage.
Declaration:
If you want to declare variables separately, you have to do it as below:
int a;
int b;
int c;
If you want to declare multiple variables in a single line, you have to do it as below:
int a,b,c;
Initialization:
If you want to initialize multiple variables in a single line, do it as below:
int a=0, b=4, c=3;
Usage:
Important thing you would like to learn here is - you can always declare 'n' number of variables without initialization.. but if you want to use any of them, they must be initialized at least once before you use them. Using them also includes even to print them.
If you won't follow any of the above mentioned points, you must get a compilation error.
Here is the code you must follow:
public class ex{
public static void main(String[] args) {
int sum = 0 , a = 1, b = 2;
int c = 1, d = 2;
if (a < b) {
sum = sum + 1;
}
if (c < b) {
sum = sum + 1;
}
System.out.println("output :"+sum);
}
}
public class TestExample {
public static void main(String args[]){
int sum = 0 ;
int a = 1;
int b = 2;
int c = 1;
int d = 2;
if (a<b) {
sum = sum+1;
}
if (c<b) {
sum = sum+1;
}
System.out.println("output :"+sum);
}
}
declaration of variable is wrong you should not declare your variable like int a,int b= 10
avoid declaration of variable on same line.
your code gives compilation error try this one it will give output as your expectation
Don't declare variables on the same line like this, even when it's compilable. It compacts your code in a way that makes it difficult to understand, especially when you name them a,b,c and d.
int sum = 0;
int a = 1;
int b = 2;
int c = 1;
int d = 2;
Change your declaration of variables to that and the rest of the code will run fine. But I would recommend reading some basic Java tutorials so you understand how to write code that compiles. I would also suggest using an IDE so these kinds of errors are flagged while you write your code.
IDEOne (with compilation errors): http://ideone.com/rYzIf5
IDEOne (without compilation errors): http://ideone.com/rYzIf5
Try this:
int sum = 0,a = 1,b = 2;
int c = 1, d = 2;
if (a<b) {
sum++;
}
if (c<b) {
sum++;
}
System.out.println("output :"+sum);

Categories