Calculating factorial with get method - java

I want to calculate the factorial of a number with a get method (I must solve a bigger problem). Here's what I tried and it returns 1:
public Sigma() {
n = -1;
}
public Sigma(int n) {
n = n;
}
private int Facto(int n) {
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
public int getFacto() {
return Facto(n);
}

The problem is that, in your constructor, you type n = n rather than this.n = n. The problem with this is that the local variable inside the constructor is assigned, rather than your class's field. this.n refers to the field n and is what you want.
You are receiving an output of 1 because the default value of all primitive number fields is 0. Using your code, 0! = 1 (which is correct), so that's your output no matter what you pass into the constructor, as the constructor ignores its parameter.
On an unrelated note, please use camelCase rather than UpperCase for method names (and field names). UpperCase should only be used for classes/interfaces/enums/annotations. Also, result = result * n may be simplified to the (almost) equivalent statement result *= n.

For the factorial you need to initialize result in the facto function, like this
private int Facto(int n)
{
int result = 1;
for (int i = 1; i <= n; i++)
{
result = result * i;
}
return result;
}

Related

Random array with size, min and max value with short

I'm doing a task where you input 3 parameters which are size, minimum value and maximum value. It then is meant to return a random number between the minimum and maximum value of the size inputted. There are also other validations such as if the min is more than the max which I've already done.
I am able to do the task using integer instead of short. As soon as I change the data type a bunch of errors come.
Below is what I've done so far, it works as expected but I am pretty sure that there is not meant to be a bottom return null, I get errors when I delete it. On the second loop, it should return the array instead of doing a system print line. The other issue is the data types at the top, it should be short maxVal and short minVal instead of int but I can't get it to work with short.
I would very much appreciate all help. Thanks!
public static ArrayList<Short> RandomArray1(int n, int maxVal, int minVal){
if(n <= 0) {
return null;
}
if(minVal > maxVal) {
return new ArrayList<Short>();
}
ArrayList<Integer> ran = new ArrayList<Integer>();
Random rand = new Random();
for(int i = 0; i < n; i++) {
int result = rand.nextInt(maxVal-minVal) + minVal;
//System.out.println(result);
ran.add(result);
}
for (int i = 0; i < ran.size(); i++) {
System.out.println(ran.get(i));
//return (ArrayList<Short>)ran.get(i);
}
return null;
I would do it like this.
first, method names by convention should start with lower case letters.
Use the method to generate the values and return the list
return interface types as opposed to implementation types (e.g. List)
throw exceptions if the arguments don't satisfy the requirements.
Note, having to cast the arguments to shorts is cumbersome but it prevents errors at compile time. Otherwise you may want to throw an additional run time exception if the values aren't within Short.MIN_VALUE and Short.MAX_VALUE.
public class RandomShorts {
public static void main(String[] args) {
List<Short> shortList = randomList(20, (short)200, (short)99);
shortList.forEach(System.out::println);
}
public static List<Short> randomList(short n, short maxVal,
short minVal) {
if (n <= 0 || minVal >= maxVal) {
throw new IllegalArgumentException(
"\nn must be > 0\nminVal must be < maxVal\n");
}
List<Short> ran = new ArrayList<>();
Random rand = new Random();
for (int i = 0; i < n; i++) {
short result =
(short) (rand.nextInt(maxVal - minVal) + minVal);
ran.add(result);
}
return ran;
}
}
If you just want to return a single random number using the supplied arguments, they you can do it like this.
public static short randomShort(int n, short maxVal, short minVal) {
return (short)((Math.random()*(maxVal - minVal))+minVal);
}
For adding the short to random list since there is not Random.nextShort(), you'll have to substitute the line
int result = rand.nextInt(maxVal-minVal) + minVal;
for
short result = (short) (rand.nextInt(maxVal-minVal) + minVal);
Where then you can add to your ran array instead of the second for loop returning the ArrayList as a short
public static short[] generateRandomShortArray (int sampleSize, short min, short max) {
short[] result = new short[sampleSize];
for (int index = 0; index < result.length; index++) {
result[index] = (short)((Math.random() * (max-min)) + min);
}
return result;
}
If an array list is required just return Arrays.asList(result);

If-statement with int: Java believes i want to convert to boolean

I'm writing a method in a class that retrieves an array and a set value from main. The aim is to locate the position of that given value and return this to main (if the value does not exist in the array it returns -1).
To my problem: when i run my code Java says: int cannot be converted to boolean. And points me to the if-statement in the code below. I tried switching the "="-sign to a ">=", and then it runs smoothly (but then it doesn't work like it's supposed to...).
Can anyone see why it thinks i want to convert it to a boolean?
public static int containsIntElement(int[] A, int val)
{
int pos = -1;
for (int i = 0; i < 10; i++)
{
if(A[i] = val)
{
pos = i;
}
}
return pos;
}
The correct way to evaluate two ints is ==, not =:
public static int containsIntElement(int[] A, int val)
{
int pos = -1;
for (int i = 0; i < 10; i++)
{
if(A[i] == val) //Note this
{
pos = i;
}
}
return pos;
}
The = operator is for assignments, so in
if(A[i] = val)
You're assigning the value val to the variable A[i], that is not a condition
Please pay attention to minor details
if(A[i] = val) // is incorrect .. in some programming language it is correct. but boy o boy it would make you cry.
if(A[i] == val) // is correct.
You use = (the assignment operator) where you intended to use == (the comparison operator).
What your if does is:
Assign val to A[i] then try (and fail) to make a logical value from A[i]
(naming conventions also say A should be lowercase)

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;
}

Java method using a for loop

I am learning Java and discovering that a little bit of knowledge is confusing.
The goal is to write a method that is the equivalent of the n! function. I am using a for loop to multiply a variable declared outside the method. All I get back is 0.
What am I doing wrong?
//
// Complete the method to return the product of
// all the numbers 1 to the parameter n (inclusive)
// # param n
// # return n!
public class MathUtil
{
public int total;
public int product(int n)
{
for (int i = 1; i == n; i ++)
{
total = total * i;
}
return total;
}
}
There is actually a lot of problems in your code:
It does not make sense to make it an instance method.
You have not initialize your total to a reasonable value.
The condition in your for loop is wrong
Method is not given a meaningful name
Messy indentation
(The list keeps growing...)
So here is a slightly improved version
public class MathUtil
{
//
// Complete the method to return the product of
// all the numbers 1 to the parameter n (inclusive)
// # param n
// # return n!
public static int factorial(int n)
{
int total = 1;
for (int i = 1; i <= n; i ++)
{
total = total * i;
}
return total;
}
}
so that you can call it as MathUtil.product(123) instead of some weird new MathUtil().product(123)
Personally I would rather do something like
result = n;
while (--n > 0) {
result *= n;
}
return result;
You are missing the initialization. Now I added the default value to 1. And you also have to change the condition. The for loop has to go on as long as the var i is smaller or equal to n.
public class MathUtil
{
public int total = 1;
public int product(int n)
{
for (int i = 1; i <= n; i ++)
{
total = total * i;
}
return total;
}
}
you didn't initialized total, therefore it's 0. Whenever you multiply 0 with anything, you will get 0 as result.
public int total = 1;
public int product(int n) {
for (int i = 1; i <= n; i++) {
total = total * i;
}
return total;
}
you havent initialized total. It defaults to 0. Then when you multiple anything with total, you get 0 as result

Incorrect return on binary to dec converter

Fixing up and tidying the converter when I noticed that it somehow gives out incorrect conversions.
For example, when creating a new number to convert using BinaryNumber bn1 = new BinaryNumber("1011"); and then asking it to give out a result with System.out.println(bn1.convertToDecimal()); it prints out 3 instead of the correct result of 11.
I'm almost sure I got the actual conversion wrong but going through it in my head I can't find the mistake.
public class BinaryNumber {
private String n;
public BinaryNumber(String pn) {
n = pn;
}
public String getN() {
return n;
}
// Creating the .convertToDecimal()
public int convertToDecimal() {
int bitPosition = 0;
int sum = 0;
for (int i = n.length() - 1; i >= 0; i--) {
sum = sum + (int) Math.pow(2, bitPosition) * (n.charAt(i) - 48);
}
return sum;
}
// Creating the .add to add the two different binary numbers after
// converting
public int add(BinaryNumber bn2) {
return convertToDecimal() + bn2.convertToDecimal();
}
// Creating the .sub to subtract the two different binary numbers after
// converting
public int sub(BinaryNumber bn2) {
return convertToDecimal() - bn2.convertToDecimal();
}
}
You just need to increment your bitposition variable.
int bitPosition = 0;
int sum = 0;
for (int i = n.length() - 1; i >= 0; i--) {
sum = sum + (int) Math.pow(2, bitPosition++) * (n.charAt(i) - 48);
}
return sum;
First of all, Java has a built in binary system, using the primitive int type. You can use this by putting 0b before the number in binary form.
If you are doing this for learning purposes, then here's what's happening:
On each iteration, the value of bitPosition is always 0, because you never update it. Of course, you want to increase it with each iteration. This can be done simply by changing
Math.pow(2, bitPosition)
to
Math.pow(2, bitPosition++)
with the ++ after the variable to change it after it is referenced.

Categories