This question already has an answer here:
Why in one case multiplying big numbers gives a wrong result?
(1 answer)
Closed 2 years ago.
I am new to Java and when I was trying to find power of number without Math.pow method I realized the answer was not right. And I want to learn why?
public class Main() {
int x = 1919;
int y = x*x*x*x;
public static void main(String[] args) {
System.out.println(y);
}
}
Output: 2043765249
But normally answer is: 13561255518721
If you go step by step, you'll see that at a moment the value becomes negative, that's because you reach Integer.MAX_VALUE which is 2^31 -1
int x = 1919;
int y = 1;
for (int i = 0; i < 4; i++) {
y *= x;
System.out.println(i + "> " + y);
}
0> 1919
1> 3682561
2> -1523100033
3> 2043765249
You may use a bigger type like double or BigInteger
double x = 1919;
double y = x * x * x * x;
System.out.println(y); // 1.3561255518721E13
BigInteger b = BigInteger.valueOf(1919).pow(4);
System.out.println(b); // 13561255518721
You're using an int for the answer, you're getting a numeric overflow.
Use double or long or BigInteger for y and you'll get the right answer.
public class Main {
public static void main(String[] args) {
System.out.println(Math.pow(1919, 4));
System.out.println((double) 1919*1919*1919*1919);
}
}
Outputs the same value.
Use long instead of int
public class Main{
public static void main(String[] args) {
long x = 1919;
long y = x*x*x*x;
System.out.println(y);
}
}
Read about variables in Java.
Related
I have the java code below which i used to calculate the Minkowski distance,
class Minkowski {
public static void main( String [] arg){
int p=2;
double [] Mski = new double[5];
double [] a = { 1, 2, 3, 4,5};
double [] b = { 6,7,8,9,11};
System.out.println(Arrays.toString(Minkowski1(a,b,p);
}
public static double Minkowski1( double [] a , double [] b, int q)
{
double sum = 0;
for(int f = 0; f < a.length; f++){
sum += Math.pow( Math.abs(a[f] - b[f]),q );
}
return Math.pow(sum, 1.0 / q);
}
The Code produce different result from a Minkowski distance matlab code :
for i=1 : 5
result2(i)=sum(abs(X(i)-Y(i)).^p).^(1/p)
end
the result in matlab is 5 5 5 5 6,and java one is not same
any suggestion please
Your problem is, that
1/q=0
in java (at least for q>1) but
1/p!=0
in matlab.
So you need to replace the integer division through floating point division and use
1.0/q
I apologise if this has already been asked before, but I was unable to find a conclusive answer after some extensive searching, so I thought I would ask here. I am a beginner to Java (to coding, in general) and was tasked with writing a program that takes a user-inputted 3 digit number, and adds those three digits.
Note: I cannot use loops for this task, and the three digits must all be inputted at once.
String myInput;
myInput =
JOptionPane.showInputDialog(null,"Hello, and welcome to the ThreeDigit program. "
+ "\nPlease input a three digit number below. \nThreeDigit will add those three numbers and display their sum.");
int threedigitinput;
threedigitinput = Integer.parseInt(myInput);
There are a number of ways, one of which would be...
String ss[] = "123".split("");
int i =
Integer.parseInt(ss[0]) +
Integer.parseInt(ss[1]) +
Integer.parseInt(ss[2]);
System.out.println(i);
another would be...
String s = "123";
int i =
Character.getNumericValue(s.charAt(0)) +
Character.getNumericValue(s.charAt(1)) +
Character.getNumericValue(s.charAt(2));
System.out.println(i);
and still another would be...
String s = "123";
int i =
s.charAt(0) +
s.charAt(1) +
s.charAt(2) -
(3 * 48);
System.out.println(i);
BUT hard coding for 3 numbers isn't very useful beyond this simple case. So how about recursion??
public static int addDigis(String s) {
if(s.length() == 1)
return s.charAt(0) - 48;
return s.charAt(0) - 48 + addDigis(s.substring(1, s.length()));
}
Output for each example: 6
you can use integer math to come up with the three numbers seperately
int first = threedigitinput / 100;
int second = (threedigitinput % 100) / 10;
int third = threedigitinput % 10;
If I understand your question, you could use Character.digit(char,int) to get the value for each character with something like -
int value = Character.digit(myInput.charAt(0), 10)
+ Character.digit(myInput.charAt(1), 10)
+ Character.digit(myInput.charAt(2), 10);
Classic example of using divmod:
public class SumIntegerDigits {
public static void main(String[] args) {
System.out.println(sumOfDigitsSimple(248)); // 14
System.out.println(sumOfDigitsIterative(248)); // 14
System.out.println(sumOfDigitsRecursive(248)); // 14
}
// Simple, non-loop solution
public static final int sumOfDigitsSimple(int x) {
int y = x % 1000; // Make sure that the value has no more than 3 digits.
return divmod(y,100)[0]+divmod(divmod(y,100)[1],10)[0]+divmod(y,10)[1];
}
// Iterative Solution
public static final int sumOfDigitsIterative(int x) {
int sum = 0;
while (x > 0) {
int[] y = divmod(x, 10);
sum += y[1];
x = y[0];
}
return sum;
}
// Tail-recursive Solution
public static final int sumOfDigitsRecursive(int x) {
if (x <= 0) {
return 0;
}
int[] y = divmod(x, 10);
return sumOfDigitsRecursive(y[0]) + y[1];
}
public static final int[] divmod(final int x, int m) {
return new int[] { (x / m), (x % m) };
}
}
I am a beginner in Java and currently going through the "how to think like a computer scientist" beginners book. I am stuck with a problem in the iteration chapter. Could anyone please point me in the right direction?
When I use math.exp, I get an answer that is completely different from the answer my code obtains.
Note, it's not homework.
Here's the question:
One way to calculate ex is to use the infinite series expansion
ex = 1 + x + x2 /2! + x3/3! + x4/4! +...
If the loop variable is named i, then the ith term is xi/i!.
Write a method called myexp that adds up the first n terms of this
series.
So here's the code:
public class InfiniteExpansion {
public static void main(String[] args){
Scanner infinite = new Scanner(System.in);
System.out.println("what is the value of X?");
double x = infinite.nextDouble();
System.out.println("what is the power?");
int power = infinite.nextInt();
System.out.println(Math.exp(power));//for comparison
System.out.println("the final value of series is: "+myExp(x, power));
}
public static double myExp(double myX, double myPower){
double firstResult = myX;
double denom = 1;
double sum =myX;
for(int count =1;count<myPower;count++){
firstResult = firstResult*myX;//handles the numerator
denom = denom*(denom+1);//handles the denominator
firstResult = firstResult/denom;//handles the segment
sum =sum+firstResult;// adds up the different segments
}
return (sum+1);//gets the final result
}
}
The assignment denom = denom*(denom+1) is going to give a sequence as follows: 1, 1*2=2, 2*3=6, 6*7=42, 42*43=...
But you want denom = denom*count.
Let's say in general we just want to print the first n factorials starting with 1!: 1!, 2!, 3!, ..., n!. At the kth term, we take the k-1th term and multiply by k. That would be computing k! recursively on the previous term. Concrete examples: 4! is 3! times 4, 6! is 5! times 6.
In code, we have
var n = 7;
var a = 1;
for (int i = 1; i <= n; i++ ) {
a = a*i; // Here's the recursion mentioned above.
System.out.println(i+'! is '+a);
}
Try running the above and compare to see what you get with running the following:
var n = 7;
var a = 1;
for (int i = 1; i <= n; i++ ) {
a = a*(a+1);
System.out.println('Is '+i+'! equal to '+a+'?');
}
There are several errors here:
firstResult should start from 1, so that it goes 1+x+x^2 instead of 1+x^2+x^3
As timctran stated you are not calculating the factorial in a correct way.
To wrap up you can simplify your operations to:
firstResult = firstResult * myX / (count+1);
sum += firstResult;
Edit:
- I ran the code and saw that Math.exp(power) is printed instead of Math.exp(x)
- My first item is wrong since sum is initialized to myX.
Why make it complicated? I tried a solution and it looks like this:
//One way to calculate ex is to use the infinite series expansion
//ex = 1 + x + x2 /2! + x3/3! + x4/4! +...
//If the loop variable is named i, then the ith term is xi/i!.
//
//Write a method called myexp that adds up the first n terms of this series.
import java.util.Scanner;
public class InfiniteExpansion2 {
public static void main(String[] args) {
Scanner infinite = new Scanner(System.in);
System.out.println("what is the value of X?");
double x = infinite.nextDouble();
System.out.println("what is the value of I?"); // !
int power = infinite.nextInt();
System.out.println(Math.exp(power));//for comparison
System.out.println("the final value of series is: " + myCalc(x, power));
}
public static double fac(double myI) {
if (myI > 1) {
return myI * fac(myI - 1);
} else {
return 1;
}
}
public static double exp(double myX, double myE) {
double result;
if (myE == 0) {
result = 1;
} else {
result = myX;
}
for (int i = 1; i < myE; i++) {
result *= myX;
}
return result;
}
public static double myCalc(double myX, double myI) {
double sum = 0;
for (int i = 0; i <= myI; i++) { // x^0 is 1
sum += (exp(myX, i) / fac(i));
}
return sum;
}
}
If you want to think like an engineer, I'd do it like this:
keep it simple
break it into pieces
stick closely to the task (like I named the var myI, not myPower - seems clearer to me, for a start - that way you won't get confused)
I hope you like it!
I tried a solution and it looks like this:
public class Fact {
public int facto(int n){
if(n==0)
return 1;
else
return n*facto(n-1);
}
}
}
import java.util.Scanner;
public class Ex {
public static void main(String[] args){
Fact myexp=new Fact();
Scanner input=new Scanner(System.in);
int n=1;
double e=1,i=0,x;
int j=1;
System.out.println("Enter n: ");
n=input.nextInt();
System.out.println("Enter x: ");
x=input.nextDouble();
while(j<=n)
{
int a=myexp.facto(j);
double y=Math.pow(x,j)/(double)a;
i=i+y;
++j;
}
e=e+i;
System.out.println("e^x= "+ e);
}
}
This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 9 years ago.
My code:
public class Test {
public static int l = 29;
public static int w = 16;
public static int total = w + l;
public static int result = w / total;
public static int Result = total * 100;
public static void main(String[] args) {
System.out.println("You're W/L ratio is: " + (Result) + "%"); // Display the string.
}
}
Response in console: You're W/L ratio is: 0%
You're doing int division which always returns an int and so w / total will always be 0 since total is always greater than w. Do the multiplication by 100 first.
int result = (w * 100) / total;
Also you will want to learn and use java naming rules. Variable names should begin with a lower case letter.
Do the calculation by casting w and total to double, or just make them double to begin with. For the first option:
public static double result = (double)w / (double)total;
whenever you do division when both numbers are integers, in result you will get integer in return.
which actually means you will get floor value of (a/b); ie:
1/2=0 as 1/2=> 0.5> floor of 0.5= 0;
3/4=0 as 3/4=> 0.75> floor of 0.75= 0;
etc
I just gave a coding interview on codility
I was asked the to implement the following, but i was not able to finish it in 20 minutes, now I am here to get ideas form this community
Write a function public int whole_cubes_count ( int A,int B ) where it should return whole cubes within the range
For example if A=8 and B=65, all the possible cubes in the range are 2^3 =8 , 3^3 =27 and 4^3=64, so the function should return count 3
I was not able to figure out how to identify a number as whole cube. How do I solve this problem?
A and B can have range from [-20000 to 20000]
This is what I tried
import java.util.Scanner;
class Solution1 {
public int whole_cubes_count ( int A,int B ) {
int count =0;
while(A<=B)
{
double v = Math.pow(A, 1 / 3); // << What goes here?
System.out.println(v);
if (v<=B)
{
count=count+1;
}
A =A +1;
}
return count ;
}
public static void main(String[] args)
{
System.out.println("Enter 1st Number");
Scanner scan = new Scanner(System.in);
int s1 = scan.nextInt();
System.out.println("Enter 2nd Number");
//Scanner scan = new Scanner(System.in);
int s2 = scan.nextInt();
Solution1 n = new Solution1();
System.out.println(n.whole_cubes_count (s1,s2));
}
}
Down and dirty, that's what I say.
If you only have 20 minutes, then they shouldn't expect super-optimized code. So don't even try. Play to the constraints of the system which say only +20,000 to -20,000 as the range. You know the cube values have to be within 27, since 27 * 27 * 27 = 19683.
public int whole_cubes_count(int a, int b) {
int count = 0;
int cube;
for (int x = -27; x <= 27; x++) {
cube = x * x * x;
if ((cube >= a) && (cube <= b))
count++;
}
return count;
}
For the positive cubes:
i = 1
while i^3 < max
++i
Similarly for the negative cubes but with an absolute value in the comparison.
To make this more general, you need to find the value of i where i^3 >= min, in the case that both min and max are positive. A similar solution works if both min and max are negative.
Well, it can be computed with O(1) complexity, we will need to find the largest cube that fits into the range, and the smallest one. All those that are between will obviously also be inside.
def n_cubes(A, B):
a_cr = int(math.ceil(cube_root(A)))
b_cr = int(math.floor(cube_root(B)))
if b_cr >= a_cr:
return b_cr - a_cr + 1
return 0
just make sure your cube_root returns integers for actual cubes. Complete solution as gist https://gist.github.com/tymofij/9035744
int countNoOfCubes(int a, int b) {
int count = 0;
for (int startsCube = (int) Math.ceil(Math.cbrt(a)); Math.pow(
startsCube, 3.0) <= b; startsCube++) {
count++;
}
return count;
}
The solution suggested by #Tim is faster than the one provided by #Erick, especially when A...B range increased.
Let me quote the ground from github here:
"one can notice that x³ > y³ for any x > y. (that is called monotonic function)
therefore for any x that lies in ∛A ≤ x ≤ ∛B, cube would fit: A ≤ x³ ≤ B
So to get number of cubes which lie within A..B, you can simply count number of integers between ∛A and ∛B. And number of integers between two numbers is their difference."
It seems perfectly correct, isn't it? It works for any power, not only for cube.
Here is my port of cube_root method for java:
/*
* make sure your cube_root returns integers for actual cubes
*/
static double cubeRoot(int x) {
//negative number cannot be raised to a fractional power
double res = Math.copySign(Math.pow(Math.abs(x), (1.0d/3)) , x);
long rounded_res = symmetricRound(res);
if (rounded_res * rounded_res * rounded_res == x)
return rounded_res;
else
return res;
}
private static long symmetricRound( double d ) {
return d < 0 ? - Math.round( -d ) : Math.round( d );
}
I am aware of Math.cbrt in java but with Math.pow approach it is easy to generalize the solution for other exponents.