The outcome of this code should be "huugiin zardal: 3", but it doesn't work.
Please help. And also is there any easy way to write it?
class Cost3{
int a;
int u;
int x;
Cost3(int a,int u,int x){
}
}
class FC1 extends Cost3{
FC1(int a1, int u1, int x1){
super(a1,u1,x1);
a=a1;
u=u1;
x=x1;
}
public int huugiin_zardal(){
return(((a+u)/2)*(x/100));
}
}
public class Cost2{
public static void main(String args[]){
FC1 h_z=new FC1(3,4,20);
System.out.println("huugiin zardal: "+h_z.huugiin_zardal());
}
}
Your problem is that ((3 + 4) / 2 ) * (20 / 100) is not 3. It is 0 because (20 / 100) is zero ... in integer arithmetic.
Indeed, even ((3 + 4) / 2 ) * 20 / 100 is 60 / 100 which is also 0. So I suspect that your root problem is that you have completely the wrong formula.
In addition, the initialization of a, u, and x should probably be in the supertype constructor not the subtype constructor. (This doesn't fix your current problem, but the way that you have the code at the moment, creating an instance of Cost3 will return an object in which the fields have not been initialized.)
((3+4)/2)*(20/100)
(7/2) * (0)
0
7/2 = 3 not 3.5 since it is truncated in integer division.
the same for 20/100 = 0 not 0.2
Indent your code better too,it helps a lot.
This is a nicer and simpler version of your code, however it will print out 0, for the integer division reasons already discussed by others:
class Cost3 {
int a;
int u;
int x;
public Cost3(int a, int u, int x) {
this.a = a;
this.u = u;
this.x = x;
}
}
class FC1 extends Cost3 {
public FC1(int a, int u, int x) {
super(a, u, x);
}
public int huugiin_zardal(){
return (((a + u) / 2) * (x / 100));
}
}
public class Cost2 {
public static void main(String args[]){
FC1 h_z = new FC1(3, 4, 20);
System.out.println("huugiin zardal: " + h_z.huugiin_zardal());
}
}
Notice that if the superclass handles the instance variables (a, u, and x), then there is no need to set them in the subclass, you just invoke the correct constructor via super().
It is hard to know exactly what your intention is, but one guess is that you want a base class (Cost3) that can handle particular variables, and have extensions (e.g. FC1) that return values based on different calculations. If so, it would be more logical to provide the base class as abstract, as follows:
class abstract Cost3 {
int a;
int u;
int x;
public Cost3(int a, int u, int x) {
this.a = a;
this.u = u;
this.x = x;
}
public abstract int calculate();
}
class FC1 extends Cost3 {
public FC1(int a, int u, int x) {
super(a, u, x);
}
public int calculate() {
return (((a + u) / 2) * (x / 100));
}
}
In your huugiin_zardal() method, all your variables are declared as int. So the division operator is performing integer division, which will silently truncate any remainder. For integer division, 20 / 100 = 0.
Just cast one of your variables to double and it will promote the entire expression to be evaluated as floating-point, only rounding to integer at the end.
How are you getting 3, and what exactly are you trying to achieve, your question is not very clear?
As for the code it will execute the following with the parameters you provided.
(((3+4)/2)*(20/100))
((7/2)*(0) // 10/100 will give you 0 unless you cast this calculation
3*0 //7/2 gets set to 3 since this is an int calculation
final answer 0.
Depending on what you are trying to achieve, you may just need to use something other than int calculations.
Related
For instance, whenever my count is equal to 4294967295 + 1 I want that the count restart from 0.
Basically I`m trying to simulate a unsigned 32 bits in java that has range [0, 4294967295]. The methods that I'm trying to create is ADD and MULTIPLE.
For example, if I have the number 4294967295 and I multiple by 2, I will get the result 4294967294.
Since Java does not have a unsigned int, I need to create that class to "simulate" the C int uint32_t in Java.
If I multiple 1103527590 * 1103515245 the result should be 4294967294, but my code is giving the result 2524872877
public class Unsigned32BitsInt {
private long limit; // Upper bound 4294967295
public Unsigned32BitsInt(long limit) {
this.limit = limit;
}
public long add(long x, long y) {
long result = 0L;
if (x + y < this.limit) {
if ((x + y) % this.limit == 0) {
result = (x + y) / 2;
} else {
result = (x + y) % this.limit;
}
} else {
if ((x + y) % this.limit == 0) {
result = (x + y) / (Math.max(x, y) / Math.min(x, y)) - 1;
} else {
result = (x + y) % this.limit - 1;
}
}
return result;
}
public long multiple(long x, long y) {
long result = 1L;
long r = x*y;
long c = result = (x * y) % this.limit;
if (x * y < this.limit) {
if ((x * y) % this.limit == 0) {
result = (x + y) / 2;
} else {
result = (x * y) % this.limit;
}
} else {
if ((x * y) % this.limit == 0) {
result = (x * y) / 2 - 1;
} else {
result = (x * y) % this.limit - 1;
}
}
return result;
}
}
Int's are only signed from the standpoint of comparisons and display. Internally signed and unsigned are no different.
So when the count is 4294967295 that is -1 in twos complement form. So you add 1 and you get 0 as required. You can print it unsigned by casting it to a long like so.
int s = -1;
// prints 4294967295
System.out.println(((long)s)&0xffff_ffffL);
If count is Integer.MAX_VALUE you have count = 2147483647 you can add 1 and get 2147483648. You can cast it to a long to print it as unsigned instead of the normal -2147483648.
To do general comparisons, use the built-in method
Integer.unsignedCompare(int x, int y);
to compare two integers as 32 bit unsigned values.
And finally,
int a = 1_103_527_590;
int b = 1_103_515_245;
System.out.println((long)(a*b) & 0xffff_ffffL);
prints
2524872878
Update
As pointed out by Andrey Tyukin instead of the casting to long and masking of the value, the Integer class method Integer.toUnsignedString() can be used to print the unsigned value. For more useful methods check out the Integer class in the Java API.
The answer from #WJS makes a good point:
[Integers] are only signed from the standpoint of comparisons and display. Internally signed and unsigned are no different.
In Java, doing arithmetic on integer types does not result in overflow.[1] The values wrap around. Along with ~unsigned methods in some of the the APIs, such as the Integer API, this makes it easy to do unsigned arithmetic.
Even so, it might be convenient to have unsigned classes. Here is part of one for a 32-bit integer:
public final class Unsigned32BitInt implements
Comparable<Unsigned32BitInt> {
public static final Unsigned32BitInt ZERO = new
Unsigned32BitInt (0);
public static final Unsigned32BitInt ONE = new
Unsigned32BitInt (1);
private final int value; // [2]
public Unsigned32BitInt () { value = 0; }
public Unsigned32BitInt (long v) {
value = (int) v ;
}
public Unsigned32BitInt (int v) {
value = v;
}
#Override
public int compareTo (Unsigned32BitInt other) {
return Integer.compareUnsigned (this.value, other.value);
}
#Override
public boolean equals (Object other) {
if (this == other) return true;
if (other == null) return false;
if ( ! (other instanceof Unsigned32BitInt )) return false;
return Integer.compareUnsigned
(this.value, ((Unsigned32BitInt) other).value) == 0;
}
#Override
public int hashCode () { return value; }
public Unsigned32BitInt add (Unsigned32BitInt i) { // [3]
return new Unsigned32BitInt (i.value + this.value);
}
public Unsigned32BitInt multiply (Unsigned32BitInt i) {
long a = i.value;
long b = value;
return new Unsigned32BitInt (a * b);
}
#Override
public String toString () {
return Integer.toUnsignedString(value);
}
}
You can continue, adding methods, including overriden methods and overloaded methods, to fit your needs.
In some cases, as shown in toString and compareTo here, methods will be wrappers for methods in the Byte, Short, Integer, or Long APIs.
NOTES:
[1] If you need arithmetic that can throw an ArithmeticException on overflow, there are ~Exact methods in the Math API
[2] I made Objects of type Unsigned32BitInt immutable. I kept the values as 32 bit integers.
[3] My preference would be to have the arithmetic operations be instance methods, e.g. c = a.add(b);, sum = sum.add(a);. From your example, you might prefer static methods. One such method might look like this:
public static Unsigned32BitInt add
(Unsigned32BitInt a, Unsigned32BitInt b) {
return new Unsigned32BitInt (a.value + b.value);
}
I tried to create a function which return a random int between x and y if x and y are integer but if x or y is a double the function return a double between x and y. But when I try with a integer it throw an Exception:
"class java.lang.Integer cannot be cast to class java.lang.Double (java.lang.Integer and java.lang.Double are in module java.base of loader 'bootstrap')"
how can I fix it?
public class Test {
public static void main(String[] args) {
System.out.print(rand(10,12.0));
}
public static<t extends Number> double rand(t x,t y) {
double a = (double) x;
double b = (double) y;
b = a < b ?(a + (b - a) * Math.random()):(b + (a - b) * Math.random());
return (x instanceof Double || y instanceof Double) ? b : (int) b;
}
}
The problem is that you are working with reference types (wrapper classes) instead of primitive types. A cast from int to double works, but a cast from Integer to Double doesn't. So you will need to find some other way to convert this.
Since you define t extends Number, you can use any method of Number for x and y.
So instead of casting to double, use this:
public static<t extends Number> double rand(t x,t y) {
double a = x.doubleValue();
double b = y.doubleValue();
I have tried:
static public void power(int n, int X) {
System.out.print( + " ");
if (n>0) {
power(n-1, X);
}
}
This does not yield a value as I'm not sure how to do that.
public int calculatePower(int base, int powerRaised)
{
if (powerRaised != 0)
return (base*calculatePower(base, powerRaised-1));
else
return 1;
}
static int power(int x, int y)
{
// Initialize result
int temp;
if( y == 0) // Base condition
return 1;
temp = power(x, y/2); // recursive calling
if (y%2 == 0) //checking whether y is even or not
return temp*temp;
else
return x*temp*temp;
}
Well others have written solution which gives you correct answer but their time complexity is O(n) as you are decreasing the power only by 1. Below solution will take less time O(log n). The trick here is that
x^y = x^(y/2) * x^(y/2)
so we only need to calculate x^(y/2) and then square it. Now if y is even then there is not problem but when y is odd we have to multiply it with x. For example
3^5 = 3^(5/2) * 3^(5/2)
but (5/2) = 2 so above equation will become 3^2 * 3^2, so we have to multiply it with 3 again then it will become 3 * 3^(5/2) * 3^(5/2)
then 3^2 will be calculated as 3^(2/1) * (3^2/1) here it no need to multiply it with 3.
public static double pow(int a, int pow) {
if (pow == 0)
return 1;
if (pow == 1)
return a;
if (pow == -1)
return 1. / a;
if (pow > 1)
return a * pow(a, pow - 1);
return 1. / (a * pow(a, -1 * (pow + 1)));
}
Considering X as number and n as power and if both are positive integers
public static int power(int n, int X) {
if (n == 0) {
return 1;
} else if(n == 1) {
return X;
} else {
return X * power(n-1, X);
}
}
Let's re-write your function:
static public void power(int n, int X) {
System.out.print( + " ");
if (n>0) {
power(n-1, X);
}
}
First of all, lets change void to int.
Afterthat, when n equals to 1, we return the result as X, because X^1 = X:
static public int power(int n, int X) {
if (n>1) {
return X * power(n-1, X);
}
return X;
}
Scanner s = new Scanner(System.in) ;
System.out.println("Enter n");
int n = s.nextInt();
System.out.println("Enter x");
int x =s.nextInt();
if (n>0){
double pow =Math.pow(n,x);
System.out.println(pow);
}
While others have given you solutions in terms of code, I would like to focus on why your code didn't work.
Recursion is a programming technique in which a method (function) calls itself. All recursions possess two certain characteristics:
When it calls itself, it does so to solve a smaller problem. In your example, to raise X to the power N, the method recursively calls itself with the arguments X and N-1, i.e. solves a smaller problem on each further step.
There's eventually a version of the problem which is trivial, such that the recursion can solve it without calling itself and return. This is called base case.
If you are familiar with mathematical induction, recursion is its programming equivalent.
Number two above is what your code is lacking. Your method never returns any number. In the case of raising a number to a power, the base case would be to solve the problem for the number 0 as raising zero to any power yields one, so the code does not need to call itself again to solve this.
So, as others have already suggested, you need two corrections to your code:
Add a return type for the method.
State the base case explicitly.
public class HelloWorld{
public long powerfun(int n,int power,long value){
if(power<1){
return value;
}
else{
value = value * n;
return powerfun(n,power-1,value);
}
}
public static void main(String []args){
HelloWorld hello = new HelloWorld();
System.out.println(hello.powerfun(5,4,1));
}
}
I've tried to add comments to explain the logic to you.
//Creating a new class
public class RecursivePower {
// Create the function that will calculate the power
// n is the number to be raised to a power
// x is the number by which we are raising n
// i.e. n^x
public static int power(int n, int x){
// Anything raised to the 0th power is 1
// So, check for that
if (x != 0){
// Recursively call the power function
return (n * power(n, x-1));
// If that is true...
}else{
return 1;
} //end if else
} //end power
// Example driver function to show your program is working
public static void main(String[] args){
System.out.println("The number 5 raised to 6 is " + power(5,6));
System.out.println("The number 10 raised to 3 is " + power(10,3));
} //end psvm
} //end RecursivePower
what is the best method of calculating the product of integer variables through method parameters? I have tried using mathematical symbols such as '*' to get a result but nothing has been successful and I am lost for answers. Any advice would be greatly appreciated, thanks in advance.
int productOfThreeNumbers(int number1, int number2, int number3){
productOfThreeNumbers(number1 * number2 * number3);
return 0;
}
If you wish to obtain an integer value from a multiplication of integers you could try
public Integer mult(int a,int b){
int c = a*b;
return c;
}
If you want to obtain a double value you could use:
public double mult(int a,int b){
double n1 = (double) a;
double n2 = (double) b;
double c = n1*n2;
return c;
}
you call the method with:
int a = 1;
int b = 2;
int c = mult(a,b);
or
int a = 1;
int b = 2;
double c = mult(a,b);
depending on which method you are using.
But looking at your code just do:
int productOfThreeNumbers(int number1, int number2, int number3){
return (number1 * number2 * number3);
}
Define TriFunction
#FunctionalInterface
interface TriFunction<A,B,C,R> {
R apply(A a, B b, C c);
}
Then, use it:
public class Main {
public static void main(String[] args) {
TriFunction<Integer, Integer, Integer, Integer> triMult = (x,y,z) -> x*y*z;
System.out.println(triMult.apply(2, 1, 3));
}
}
public class Rational {
int num, denom; /*I'm building an object named "Rational, which takes in two int values, num and denom, and represent them as a rational number(num/denom)*/
public Rational(int a, int b){//this is the constructor
this.num = a;
this.denom = b;
}
public Rational(){//this is just another form of constructor
this.num = 0;
this.denum = 0;
}
public static void printRational(Rational x){/*this is the method that prints the rational number in a fractional format*/
System.out.println(x.num+"/"+x.denom);
}
public static int gcd(int a, int b){/*this is the method which finds the greatest common denominator of numerator of denominator. This will be used to simplify the fraction*/
if(b == 0){
return a;
}
else{
return gcd(b, a%b);
}
}
public static Rational add(Rational x, Rational y){/*this is a method which adds the two rational numbers(or objects) together, then simplify it utilizing the gcd method*/
Rational z = new Rational();
z.denom = (x.denom * y.denom);
z.num = y.num*x.denom + x.num*y.denom;
z.denom = z.denom/gcd(z.num, z.denom);
z.num = z.num/gcd(z.num, z.denom);
return z;
}
public static void main(String[] args) {
Rational y = new Rational(1, 2); //1st Rational Object: y
Rational z = new Rational(2, 6); //2nd Rational Object: z
printRational(add(y, z)); //implementing the method
//result? so far so good. I get the correct result
}
}
The problem I'm facing is I don't understand is that why this won't work instead and give me an error.
public static Rational add(Rational x, Rational y){
Rational z = new Rational();
int a = (x.denom * y.denom);
int b = y.num*x.denom + x.num*y.denom;
z.denom = a/gcd(z.num, z.denom);
z.num = b/gcd(z.num, z.denom);
return z;
}
Why would this give me an error message: "Exception in thread "main" java.lang.ArithmeticException: / by zero
at Rational.add(Rational.java:47)
at Rational.main(Rational.java:58)" when the instances of the object are int types and I'm temporarility storing the value into int a, b; Help me please if you see something I don't see!! Thank you.
I do not know what is the exact problem, when you say "It is not working". It would have been helpful if you could tell what error is it giving. However, from what you have said, Could it be because you have not initialized z.num and z.denom and are sending them to gcd() ?? They will both be zero, as they are primitive data type "int" so your gcd method will return 0 and cause an exception.
public static Rational add(Rational x, Rational y){
Rational z = new Rational();
int a = (x.denom * y.denom);
int b = y.num*x.denom + x.num*y.denom;
z.denom = a/gcd(z.num, z.denom); <--------------
z.num = b/gcd(z.num, z.denom); <--------------
return z;
}
You are using the wrong implementation for dividing with gcd as the number changes in this case.
z.denom = z.denom/gcd(z.num, z.denom);
z.num = z.num/gcd(z.num, z.denom);//z.denom is changed here.
The z.denom can be 0 as it is changed so gcd is 0 and hence the exception.
So what you can do is.
int gcd = gcd(z.num, z.denom);
z.denom /= gcd;
z.num /= gcd;
Also this fails when either of num or denom is a 0.