Using iteration to work out powers - java

I'm basically trying to rewrite math.pow, I have the following obviously I'm not getting the concept of returning values. What exactly am I doing wrong?
public static int power(int x, int n)
{
if (n == 0) return 1;
int i,total;
for(i = 0; i < n-1 ;i++);
{
total = (x * total);
}
return total;
}

You need to initialize total to 1.
int total = 1;
You can just rewrite everything to:
public static int power(int x, int n)
{
int total = 1;
for(int i = 0; i < n; i++) // i can be declared here directly
{
total = (x * total);
}
return total; // total remains 1 if n = 0
}

public static int power(int x, int n)
{
int total = 1; // Initialized total to 1
for(int i = 0; i < n; i++)
{
total = x*total;
}
return total;
}

instead of i < n-1 you should use i <= n-1 or i < n and int total=1. hope it will work.
also remove ; from the for loop end. rewriting the code
public static int power(int x, int n){
int total=1;
for(int i = 0;i < n;i++)
total *= x;
return total;
}

For one, it looks like you meant:
if (n == 0) return 1;
check the power, not the base number.
You're not initialisign total either, using total = x would fix things i think.

The variable total starts at 0. So calling total = x*total will always be 0.
You need to initialize total to x.

Here is a solution with log(n) complexity instead of linear. Be careful with overflow though.
int pow(int x, int n) {
int res = 1;
while(n > 0) {
if(n % 2 == 1) {
res = res * x;
}
x = x * x;
n = n / 2;
}
return res;
}

Related

How can I swap 2 digits (i,j) from a n number?

basically i have an integer n = 23456 and i want to swap the second and fourth digit, so i = 2 and j = 4. So the output would be 25436. I canĀ“t use any Java class, so I supose that one of the ways to do it is by divide the number on powers of 10 and keep the rest on a new variable.
this is what i have so far:
public static int powerOfTen(int n) {
int p = 10;
while(n-1 > 0) {
p = p*10;
n--;
}
return p;
}
public static int swapNum(int n, int i, int j) {
int swap = 1;
int count = numDigits(n);
int digit1 = nDigit(n, i);
int digit2 = nDigit(n, j);
if(i > j) {
swap = n/powerOfTen(i);
int rest = n%powerOfTen(i);
rest = rest/10;
swap = swap*powerOfTen(i);
}
}
Here's your code with some modifications:
public class Main
{
// Count the number of digits in an integer
static int numDigits(int n)
{
if (n == 0) return 1;
int count = 0;
while (n != 0) {
count++;
n /= 10;
}
return count;
}
// Reverse an integer
static int reverseNumber(int n)
{
int result = 0;
while (n != 0) {
result = result * 10 + n % 10;
n /= 10;
}
return result;
}
// Get the nth digit - from the left
static int nDigit(int n, int index)
{
n = reverseNumber(n);
for (int i = 0; i < index; i++) {
n /= 10;
}
return n % 10;
}
static int swapNum(int n, int i, int j)
{
// Make indexes 0-based
i = i - 1;
j = j - 1;
int count = numDigits(n);
int digit1 = nDigit(n, i);
int digit2 = nDigit(n, j);
int result = 0;
for (int k = count - 1; k >= 0; --k) {
int digit;
// Get the correct digit, i, j, or current
if (k == i) digit = digit2;
else if (k == j) digit = digit1;
else digit = n % 10;
result = result * 10 + digit;
n /= 10;
}
return reverseNumber(result);
}
public static void main(String[] args) {
System.out.println(swapNum(12345678 , 4, 5));
}
}
You can't use any class? what about convert number to char array, swap and parse it back?
// helper function to convert char array to int
public static int parseInt(char[] chars) {
int result = 0; // accumulator
int idx_value = 1; // power of ten counter
for (int i = chars.length - 1; i >= 0; i--) { // loop from tail to head
// char - '0' mean it will convert '0' to 0 and '1' will be 1 so on.
result += (chars[i] - '0') * idx_value;
idx_value *= 10;
}
return result;
}
public static int swapNum(int n, int i, int j) {
// convert number to char array
char[] chars = ("" + n).toCharArray();
// use zero based index
i-=1;j-=1;
// perform swap
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
// convert char array back to int
return parseInt(chars);
}

Implementation of sinus function | Calculation Time

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.

Implementing my own pow function in Java

This is a popular interview question. Implementing my own pow function.
There are some popular recursive approaches available online but I'm trying to do it iteratively. The code works for n > 0, but I'm a little lost when it gets below 0. Here's my code.
public double myPow(double x, int n) {
if(x == 0) return 0;
if(n == 0) return 1;
double result = 1;
if(n > 0 ){
for(int i=1; i <= n; i++){
result = result * x;
}
}else{
for(int i=1; i<= n; i++){
//calculate the nth root
}
}
return result;
}
Any help appreciated with calculating the nth root.
I guess you can do that: (because x^(-n) = 1/x^n)
double positive_pow(double x, int n) {
if(x == 0) return 0;
if(n == 0) return 1;
double result = 1;
if(n > 0 ){
for(int i=1; i <= n; i++){
result = result * x;
}
}else{
for(int i=1; i<= n; i++){
//calculate the nth root
}
}
return result;
}
public double pow(double x, int n) {
if (n > 0) return positive_pow(x, n);
else if (n == 0) return 1;
else return 1 / positive_pow(x, 0-n);
}
This is not the shortest way to implement this, but it is based on your base function and it's more clear than recursively calculating it or messing around with Math functions.
This will work.
This code will be returning result for negative powers as well. For the explanation I have used the variable int p= x for my calculation of negative powers.....
public static double Pow(int x,int n){
if(x == 0) return 0;
if(n == 0) return 1;
double result = 1;
if(n > 0 ){
for(int i=1; i <= n; i++){
result = result * x;
}
}
else{
int p=x;
for(int i=0; i>n; i--){
if(result==1){
result= 1/(result*x);
result++;
}
else{
p=p*x;
result= (1.0)*1/p;
}
}
}
return result;
}
Try this, I wrote this one when I was practicing Java. The idea is 5^62=5^(32+16+8+4+2)=5^32*5^16*5^8*5^4*5^2, and in binary code, 62 is 00111110.
Here is the code:
double pow(double x, int n){
int i;
double result;
result = 1;
i = x;
while(n != 0){
if(n & 1 == 1){
result *= i;
}
i *= i;
n>>1;
}
return result;
}

Missing return statement (Java): Calculating first 100 pentagonal number)

I am trying to find the first 100 pentagonal numbers using methods. Below is my code, however, I keep getting missing return statement. I sure that I am not placing return statement at the appropriately, besides I wouldn't know if the process is right. I would therefore appreciate guidance. Thank you.
PS: yet to learn arrays and this is no homework
public class PentagonNumber {
public static void main(String[] args) {
int numberperline = 10;
int n = 1;
int count = 0;
int pent = getpentagonnumber(n);
count++;
if (count % numberperline == 0)
System.out.println();
else System.out.print(pent + "\t");
}
public static int getpentagonnumber(int x) {
for (int count = 0; count < 100; count++) {
for (x = 1; x <= 100; x++) {
int result;
result = x * (3 * x - 1) / 2;
return result;
}
}
}
}
Your code should be changed like this:
public class PentagonNumber {
public static void main(String[] args) {
int numberperline = 10;
//int n = 1; // you do not need N
//int count = 0; // you do not this either
for (x = 0; x < 100; x++) { // moved
int pent = getpentagonnumber(x+1); // +1 so it goes 1::100
//count++;
if (x % numberperline == 0)
System.out.println();
//else // you were skipping every tenth result.
System.out.print(pent + "\t");
}// close for
}
public static int getpentagonnumber(int x) {
//for (int count = 0; count < 100; count++) { // moved
//for (x = 1; x <= 100; x++) { // removed
int result; // no need to declare and then calculate
result = x * (3 * x - 1) / 2; // but not wrong either.
return result;
//}
//}
}
}
You only have a return value inside a for loop. You probably meant for it to be:
public static int getpentagonnumber(int x ){
int result = 0;
for (int count=0; count<100; count++){
for (x=1;x<=100;x++){
result = x*(3*x-1)/2;
}
} //this was missing
return result;
}

Project Euler 14 Java

I have been having trouble on Problem 14 on Project Euler. I don't understand why my code(Java) isn't working and any help would be appreciated.
public class Calculate {
public static void main(String[] args){
System.out.println(calc());
}
public static int calc(){
int max = 0;
int maxI = 0;
for (int i = 0; i < 1000000; i++){
if (seqLen(i) >= max){
max = seqLen(i);
maxI = i;
}
}
return maxI;
}
public static int seqLen(int seed){
if (seed <= 0) return 0;
if (seed == 1) return 1;
int len = 1;
if (seed % 2 == 0){
len += seqLen(seed/2);
}
else{
len += seqLen((3*seed)+1);
}
return len;
}
}
Thanks!
You run into an overflow with your int variables.
The maximum number appearing in this computation (when using a brute force approach) is 56991483520.
Java's int maximum value is 2^31-1 == 2147483647, which is obviously smaller.
So change your variables etc to use long. Here the max value is 2^63-1 == 9223372036854775807, which will be fitting for all values.
You are breaking the int limit.
Using long:
public static long calc() {
long max = 0;
long maxI = 0;
for (long i = 0; i < 1000000; i++) {
long len = seqLen(i);
if (len >= max) {
max = len;
maxI = i;
}
}
return maxI;
}
public static long seqLen(long seed) {
if (seed <= 0) {
return 0;
}
if (seed == 1) {
return 1;
}
long len = 1;
if (seed % 2 == 0) {
len += seqLen(seed / 2);
} else {
len += seqLen((3 * seed) + 1);
}
return len;
}
public void test() {
System.out.println(seqLen(13));
System.out.println(calc());
}
Gives you the correct result of 837799.
Note that there are better/more efficient algorithms than this one.
Actually, you don't have to check from 1 to 499999.
You only need to check from 500000 to 999999
because the next step of any even number between 500000 and 999999
is going to be some integer from 1 to 499999.
That means that an integer from 1 to 499999 cannot be the answer.
So change the for loop to the following
for (int i = 500000; i < 1000000; i++) {
}
And "i" doesn't have to be long
while "seed" has to be long.

Categories

Resources