i need to take 2 inputted numbers and calculate variable 1 to the power of variable 2 is without using math.pow and using a for loop. This is what i have now
Scanner in = new Scanner(System.in);
System.out.print("Please enter your base: ");
int base = in.nextInt();
System.out.print("Please enter your exponent: ");
int power = in.nextInt();
int result = mathPower(base, power);
System.out.println(base + " to the power of " + power + " is " + result + ".");
}
public static int mathPower(int a, int b)
{
int result = a;
if (b == 0) {
result = 1;
}
if (b < 0) {
a = (1 / a);
b = -b;
}
for (a = 1; a < b; a++) {
result = result * a;
return result;
}
return result;
}
}
It only seems to work if the exponent is 0, otherwise it just displays the a value. I need both positive and negative exponents. Thanks in advance!
The case with b<0 only makes sense with floating point numbers, so I changed the type of a and the return value to double.
public static double mathPower(double a, int b)
{
double result = 1;
if (b < 0) {
a = 1.0 / a;
b = -b;
}
for (int i = 0; i < b; i++) {
result = result * a;
}
return result;
}
You have three main problems:
The return statement inside the loop is breaking it in the first repetition.
You're using your a variable as the loop variable.
If you allow negative exponents then the return value should be a double.
public static double mathPower(double a, int b)
{
double result = 1.0;
if (b == 0)
{
result = 1.0;
}
if (b < 0)
{
a = (1.0 / a);
b = -b;
}
for (int i = 0; i < b; i++)
{
result = result * a;
}
return result;
}
suppose you have numb1=2 and numb2=6.
then
temp=1;
if (numb2 < 0) {
numb1 = 1 / numb1;
numb2 = -numb2;
}
for(int n = 1; n<=numb2; n++){
temp=temp*numb1;
}
public double power(double base,int pow)
{
double result = 1;
if(pow==0)
return 1;
if(base == 0)
return 0;
if(pow>0)
{
for(int i = 0;i<pow;i++)
{
result *= base;
}
}
else
{
for(int i = pow;i<0;i++)
{
result *= base;
}
result = 1/result;
}
return result;
}
Related
Can anybody tell me why this code doesn't work? I'm trying to implement a sinus-function with a given limitation of precision (by the error-variable).
Certain details about the calculation are given here: https://en.wikipedia.org/wiki/Taylor_series
berechnePot calculates the potence
berechneFak calculates the faculty
berechneVZW calculates the pre sign (plus or minus)
I don't get the point, why the function is calculating that slow.
public class Sinus {
public static double sinus(double x) {
double error = 0.001;
double summand = 0;
double sum = 0;
int k = 0;
do {
double pot = 0;
double fak = 0;
pot = berechnePot(x, k);
fak = berechneFak(k);
summand = pot / fak;
berechneVZW(summand, k);
sum += summand;
k++;
} while (abs(summand) > error);
return sum;
}
public static double abs(double value) {
if (value < 0) return -value;
else return value;
}
public static double berechneVZW(double value, int k) {
if (k % 2 == 0) {
return value;
} else {
return value *= (-1);
}
}
public static double berechnePot(double x, double k) {
double pot = 0;
pot += x;
for (int i = 0; i <= k; i++) {
pot *= (x * x);
}
return pot;
}
public static double berechneFak(int k) {
double fak = 1;
if (k == 0) {
return 1;
} else {
for (int i = 0; i <= k; k++) {
fak *= (2 * i + 1);
}
}
return fak;
}
}
Finally i got to the right solution..
I hope that the new structure helps you to better understand my implementation better.
Thanks for all your help!
public class Sinus {
public static double sinus(double x) {
double error = 0.00001;
double summand = 0;
double result = 0;
double fak = 0;
int k = 0;
do {
double pot = 0;
pot = calcNumeratorPotency(x, k);
fak = calcDenumeratorFaculty(k);
summand = pot / fak;
summand = definePreSign(summand, k);
result += summand;
k++;
} while (absoluteValue(summand) > error);
return result;
}
public static double absoluteValue(double value) {
if (value < 0)
return -value;
else
return value;
}
public static double definePreSign(double value, int k) {
if (k % 2 == 0) {
return value;
} else {
return value * (-1);
}
}
public static double calcNumeratorPotency(double x, double k) {
double pot = x;
for (int i = 0; i < 2 * k; i++) {
pot *= x;
}
return pot;
}
public static double calcDenumeratorFaculty(int k) {
double fak = 1;
if (k == 0) {
return 1;
} else {
for (int i = 1; i <= (2 * k + 1); i++) {
fak *= i;
}
}
return fak;
}
You seem to have worked with another language before. Java works a bit different than you seem to expect.
for (int i = 0; i <= k; k++) {
fak *= (2 * i + 1);
}
This particular loop is definetly not working as expected. You increment k, but iis supposed to grow? Might be you want to write:
for (int i = 0; i <= k; i++) {
fak *= (2 * i + 1);
}
Because the loop counts k, instead of i, it continues, until k overruns the integer-range and becomes Integer.MIN_VALUE. At that point, your loop finally terminates. :)
On a completely different note, and meant as constructive critique: You might want to take a look at the default Java-Style-Guide (https://github.com/twitter/commons/blob/master/src/java/com/twitter/common/styleguide.md)
Small excerpt:
// Bad.
// - This offers poor visual separation of operations.
int foo=a+b+1;
// Good.
int foo = a + b + 1;
Spaces between identifiers and operators are very, very helpful, operating with numbers, but also with a lot of different stuff.
It is not quite clear to me what you are calculating in berechnePot and berechnePot. They seem to be the numerators and denominators, judging from the context.
Running your code with a debugger, I can see that summand is calculated very wrongly, and decreases very slowly. This is the reason why it takes so long.
The Math class provides a pow method, so you don't really need to use a for loop to calculate powers. I think you might be overcomplicating this a bit. I would write a getSummand method and a factorial method:
private static double getSummand(double x, int k) {
int power = k * 2 + 1;
double numerator = Math.pow(x, power);
double denominator = factorial(power);
int sign = k % 2 == 1 ? -1 : 1;
return numerator / denominator * sign;
}
private static double factorial(int x) {
double result = 1;
for (int i = 1; i <= x; i++) {
result *= i;
}
return result;
}
And use them like this:
public static double sinus(double x) {
double error = 0.001;
double summand = 0;
double sum = 0;
int k = 0;
do {
summand = getSummand(x, k);
sum += summand;
k++;
} while (Math.abs(summand) > error);
return sum;
}
If this is an assignment and you are not allowed to use anything from the Math class, you could write your own pow method like this:
private static double pow(double x, int p) {
double result = 1;
for (int i = 0 ; i < p ; i++) {
result *= x;
}
return result;
}
In your berechneFak() function you have a loop inside the else clause. You do increment k but not i so i <= k is always true. Try looking at it in a debugger. This is the loop that is slowing it down.
So every time k will count up to the max integer value of 2,147,483,647 in single increments and then overflow to a negative value at which point the loop will end.
Just to clarify: I did not look at if the math is correct but just at why the program is slow.
I can't figure out why, but when the power function is used, it adds a (what seems to be random) integer into the middle of the answer. I can't figure out why, can any of you see anything unusual? Thanks
//multiplication method
public IntValue Multiply(IntValue multiplier) {
StringBuilder product = new StringBuilder();
int pos = 0;
for (int i = multiplier.getValue().length() - 1; i >= 0; i--) {
int currentPosition = pos++;
int carry = 0;
int multiplierDigit = Character.getNumericValue(multiplier.getValue().charAt(i));
for (int j = value.length() - 1; j >= 0; j--) {
int multiplicandDigit = Character.getNumericValue(value.charAt(j));
int tempProduct = currentPosition < product.length()
? Character.getNumericValue(product.charAt(currentPosition)) : 0;
int currentProduct = (multiplicandDigit * multiplierDigit) + carry + tempProduct;
if (currentProduct > 9) {
carry = currentProduct / 10;
currentProduct = currentProduct % 10;
}
if (currentPosition < product.length()) {
product.setCharAt(currentPosition, Character.forDigit(currentProduct, 10));
} else {
product.append(currentProduct);
}
++currentPosition;
}
if (carry > 0) {
if (currentPosition < product.length()) {
product.setCharAt(currentPosition, Character.forDigit(carry, 10));
} else {
product.append(carry);
}
}
}
return new IntValue(product.reverse().toString());
}
//number1 and number2 are IntValues.
//power method
public IntValue Power(long n) {
IntValue result = new IntValue("1");
for(int i = 0; i < n; i++) {
result = result.Multiply(this);
}
return result;
}
System.out.println("Result = "+number1.Power(Long.parseLong(number2.toString())));
Try the following code:
BigInteger number1 = new BigInteger("5");
System.out.println("Result = " + number1.pow(5).toString());
It's how we do it in java.
There is a library for working with powers in Java, namely Math.pow (for small numbers) and BigInteger pow (for arbitrary large numbers). Note that BigInteger power cannot compute fractional powers.
There are iterative DIY algorithms for fractional powers as well, for example
BigInteger sqrt(BigInteger n) {
BigInteger a = BigInteger.ONE;
BigInteger b = new BigInteger(n.shiftRight(5).add(new BigInteger("8")).toString());
while(b.compareTo(a) >= 0) {
BigInteger mid = new BigInteger(a.add(b).shiftRight(1).toString());
if(mid.multiply(mid).compareTo(n) > 0) b = mid.subtract(BigInteger.ONE);
else a = mid.add(BigInteger.ONE);
}
return a.subtract(BigInteger.ONE);
}
I need some help on a program i'm supposed to create. i'm supposed to create a program that reads two strings of any length that are user inputted and it subtracts or adds them together. i'm NOT allowed to convert these strings into numbers before the operation. this is what I got so far.My teacher mentioned something like converting the strings into uni-code to add and subtract them but i have no idea how to do it as we haven't even learned uni-code. HERE IS MY CODE:
import java.util.Scanner;
public class Number {
private char Sign;
private String Whole;
private String Fraction;
public static void main(String[] args) {
Scanner Keyboard = new Scanner (System.in);
System.out.println("This program adds or subtracts numbers of any lengths, please add two numbers: ");
String num1 = Keyboard.nextLine();
System.out.println("Enter the second number: ");
String num2 = Keyboard.nextLine();
String sum = " ";
int length = num1.length();
int carry = 0;
public Number Add(Number RHS) {
for (int i = length -1 ; i >= 0; i--) {
char c1 = num1.charAt(i);
char c2 = num2.charAt(i);
int tempSum = (c1 - 48) + (c2 - 48) + carry;
carry = tempSum / 10;
int sumDigit = tempSum % 10;
sum = (char) (sumDigit + 48) + sum;
if (carry == 1) {
sum = "1" + sum;
}
}
}
}
public Number (double n) {
Whole = " ";
Fraction = " ";
if (n >= 0) {
Sign = '+';
}
else
{
Sign = '-';
n = Math.abs(n);
String numString = new Double(n).toString();
int position = numString.indexOf(".");
}
}
}
public static String add(String as, String bs){
ArrayList<String> BigNum = new ArrayList<>();
int m = as.length()-1;
int n = bs.length()-1;
int min = m > n ? n : m ;
int max = 0;
String s;
if(n > m){
s = bs;
max = n;
}else{s = as ; max = m;}
Integer carry = 0;
while(true){
int a = Integer.parseInt(Character.toString(as.charAt(m)));
int b = Integer.parseInt(Character.toString(bs.charAt(n)));
Integer c = a + b + carry;
if(c > 9){
carry = 1;
c %=10;
}else carry = 0;
BigNum.add(c.toString());
n--; m--; min--; max--;
if ( min < 0 ) {
if(carry !=0 && max < 0 )
BigNum.add(carry.toString());
break;
}
}
Integer c = carry;
while(max >= 0) {
c += Integer.parseInt(Character.toString(s.charAt(max)));
BigNum.add(c.toString());
c = 0;
max--;
}
String s2 = "";
for (int i = BigNum.size()-1; i >= 0; i--) {
s2 +=BigNum.get(i);
}
return s2;
}
I am trying to find the sum of the even Fibonacci numbers up untill 4 million.
I found the numbers but i can't get them add up... in the if(n % 2 ==0) loop
8
34
144
610
2584
10946
46368
196418
832040
3524578
public static void number2()
{
int number = 40;
int a, b, c;
int numLim = 0;
a = 1;
b = 2;
while(numLim < 4000000)
{
c = a + b;
a = b;
b = c;
numLim = b;
if(numLim > 4000000)
{
break;
}
int sum = 0;
if(numLim % 2 == 0)
{
System.out.println(numLim);
sum = sum + numLim;
System.out.println("sum :" +sum);
}
}
}
You must define sum outside the while loop, or it will become 0 each iteration.
int sum = 0;
...
while ...
Remember not to set sum to 0 each iteration.
public class Euler2 {
public static void main(String[] args) {
int fibonacci;
int num = 0;
int num2 = 1;
int loop;
int sum = 0;
System.out.println(num2);
for (loop = 0; loop <= 32; loop++) {
fibonacci = num + num2;
num = num2;
num2 = fibonacci;
System.out.println("Fibonacci number : " + fibonacci);
sum += fibonacci;
System.out.println("This is the sum " +sum);
}
}
}
So I solved it like this, it's a little more efficient and the math works but Euler hates me, hope this helps.
public class Euler2 {
public static void main(String[] args) {
int fibonacci;
int num = 0;
int num2 = 1;
int loop;
int sum = 0;
System.out.println(num2);
for (loop = 0; loop <= 31; loop++) {
fibonacci = num + num2;
num = num2;
num2 = fibonacci;
System.out.println("Fibonacci number : " + fibonacci);
if (fibonacci%2 == 0) {
sum += fibonacci;
System.out.println(sum);
}
}
}
Sorry, this code works.
Tried doing the above in Java and here is my solution that works
public static void main(String[] args) {
int first = 1;
int second = 2;
int sum = 0;
int sumOfEvenValuedTerms = second;
for (int i = 0; i < 30; i++) {
sum = first + second;
if (sum <= 4000000) {
if (sum % 2 == 0) {
sumOfEvenValuedTerms += sum;
}
first = second;
second = sum;
}
}
System.out.println(sumOfEvenValuedTerms);
}
Output is 4613732
public static int getSumOfEvenNumbers(int n) {
int prev = 0;
int i =1;
int sum = 0;
while (i<n){
int nextNumber = i + prev;
if(nextNumber %2 ==0) {
System.out.println(nextNumber);
sum +=nextNumber;
}
prev = i;
i = nextNumber;
}
return sum;
}
public class evenFib {
public static void main(String[] args) {
double a = 1, b = 2, c = 0, sum = 0;
for (double i = 0; i <= 1000; i++) {
c = a + b;
a = b;
b = c;
if (c % 2 == 0 && sum < 4000000) {
sum = sum + c;
}
}
System.out.println(sum + 2);
}
}
i am trying to not import the math class to use but i am still trying to estimate the constant "e". it is said e= 1+(1/1!)+(1/2!)+(1/3!)+(1/4!)+(1/5!)+.....
these are what i have int at the top
String userInput;
int uIp; // this converts the string into int type
double e = 2;
then i ask some questions then i check to see not zero to exit and non negative to continue
While(uIp >0){
final int endTheLoop = 15;
int factorialNumber = 1;
double e2TheUserInput=0;
for(int i = 2; i < endTheLoop; i++){
for(int j = 1; j < i; j++){
factorialNumber = ((i - 1) * factorialNumber);
}
e = (1/factorialNumber) + e;
e2TheUserInput = Math.pow(e,uIp);
}
}
You are doing integer division(but e is a double right?):
e = (1/factorialNumber) + e;
Correct that to:
e = (1.0/(double)factorialNumber) + e;
It was counting all the loops, but changes are zero according to the integer division. :)
e= 2+(0)+(0)+(0)+(0)+.....
I am not sure what your code is trying to do but if you want to compute exp(x) this is how I would do it.
public static void main(String... args) {
for (int i = -4; i <= 4; i++)
System.out.println(i + ": " + exp(i) + " cf " + Math.exp(i));
}
private static double exp(double d) {
if (d < 0)
return 1 / exp(-d);
double e = 1, term = 1;
for (int i = 1; i < 20 || term > e * 1e-16; i++) {
term *= d / i;
e += term;
}
return e;
}
For large exponents, it more efficient to evaluate the integral powers without using a taylor series.
public static final double E = 2.7182818284590452354;
private static double exp(double d) {
if (d < 0)
return 1 / exp(-d);
long num = (long) d;
double numE = 1;
double mult = E;
while (num > 0) {
if ((num & 1) != 0)
numE *= mult;
num >>>= 1;
mult *= mult;
}
double fract = d - (long) d;
double fractE = 1, term = 1;
for (int i = 1; i < 20; i++) {
term *= fract / i;
fractE += term;
}
return numE * fractE;
}