Why does my arraylist stay empty despite adding objects? - java

I'm trying to make a method that factorizes the number n into the product of primes. For example factorizing 12 would result in 3 x 2^2. The first block of code factorizes n into loose numbers so 12 = 3 x 2 x 2 and places them in f. The second block is then supposed to store these numbers in p as powers instead of loose numbers by counting the exponent as the amount of times a number occurs in f, so 3^1 x 2^2 instead of 3 x 2 x 2. This is done with an object Power which stores the base and exponent of a number.
For some reason however, this code keeps returning empty arrays. And after looking it over many times I still have no idea why this would be the case. Is there something I'm doing wrong or that I misunderstand?
/**
* factorize n
*
* #param n the number to 'powerize'
* #modifies none
* #pre {#code 2 <= n}
* #return factorization of n
*/
public static List<Power> factorize(int n) {
List<Integer> f = new ArrayList<Integer>(); // f are factors
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
f.add(i);
n /= i;
}
}
List<Power> p = new ArrayList<Power>(); // p are the factors with powers
for (int j = 2; j <= n; j++) { //j will be the base
int e = 0; //exponent
for (int k = 0; k <= f.size(); k++) {
if (f.get(k) == j) {
e++;
}
}
p.add(new Power(j, e));
}
return p; //returns factors in powered form
}
I'll add the code for the Power object in case it's necessary.
/**
* Record containing a base and an exponent.
*
* #inv {#code 0 <= base && 0 <= exponent}
*/
public static class Power { // BEGIN RECORD TYPE
/**
* The base.
*/
public int base;
/**
* The exponent.
*/
public int exponent;
/**
* Constructs a Power with given base and exponent.
*
* #param base the base
* #param exponent the exponent
* #pre {#code 0 <= base && 0 <= exponent}
* #post {#code \result.base == base && \result.exponent == exponent}
*/
public Power(int base, int exponent) {
this.base = base;
this.exponent = exponent;
}
} // END RECORD TYPE

if you debug you will see that your n variable value is 1 after first for cycle. That's why second cycle not started at all

Related

Power and factorial series sum Explanation

Question:
A class SeriesSum is designed to calculate the sum of the following series:
Class name : SeriesSum
Data members/instance variables:
x : to store an integer number
n : to store number of terms
sum : double variable to store the sum of the series
Member functions:
SeriesSum(int xx, int nn) : constructor to assign x=xx and n=nn
double findfact(int m) to return the factorial of m using recursive
technique.
double findpower(int x, int y) : to return x raised to the power of y using
recursive technique.
void calculate( ) : to calculate the sum of the series by invoking
the recursive functions respectively
void display( ) : to display the sum of the series
(a) Specify the class SeriesSum, giving details of the constructor(int, int),
double findfact(int), double findpower(int, int), void calculate( ) and
void display( ).
Define the main( ) function to create an object and call the
functions accordingly to enable the task.
Code:
class SeriesSum
{
int x,n;
double sum;
SeriesSum(int xx,int nn)
{ x=xx;
n=nn;
sum=0.0;
}
double findfact(int a)
{ return (a<2)? 1:a*findfact(a-1);
}
double findpower(int a, int b)
{ return (b==0)? 1:a*findpower(a,b-1);
}
void calculate()
{ for(int i=2;i<=n;i+=2)
sum += findpower(x,i)/findfact(i-1);
}
void display()
{ System.out.println("sum="+ sum);
}
static void main()
{ SeriesSum obj = new SeriesSum(3,8);
obj.calculate();
obj.display();
}
}
MyProblem:
I am having problems in understanding that when i= any odd number (Taking an example such as 3 here)then it value that passes through findfact is (i-1)=2 then how am I getting the odd factorials such as 3!
Any help or guidance would be highly appreciated.
Optional:
If you can somehow explain the recursion taking place in the findpower and findfactorial,it would be of great help.
Take a closer look a the loop. i starts at 2 and is incremented by 2 every iteration, so it is never odd. It corresponds to the successive powers of x, each of which is divided by the factorial of i -1 (which IS odd).
As for the recursion in findfact, you just need to unwrap the first few calls by hand to see why it works :
findfact(a) = a * findfact(a -1)
= a * (a - 1) * findfact(a -2)
= a * (a - 1) * (a - 2) * findfact(a - 3)
...
= a * (a - 1) * (a - 2) * ... * 2 * findfact(1)
= a * (a - 1) * (a - 2) * ... * 2 * 1
= a!*
The same reasoning works with findpower.
As a side note, while it may be helpful for teaching purposes, recursion is a terrible idea for computing factorials or powers.
I'm not sure I understand your question correctly, but I try to help you the best I can.
I am having problems in understanding that when i= any odd number
In this code i never will be any odd number
for(int i=2;i<=n;i+=2)
i will be: 2 , 4 , 6 , 8 and so on because i+=2
The Recursion
The findfact() function in a more readable version:
double findfact(int a){
if(a < 2 ){
return 1;
} else {
return a * findfact(a - 1);
}
}
you can imagine it as a staircase, every call of findfact is a step:
We test: if a < 2 then return 1 else we call findfact() again with a-1 and multiply a with the result of findfact()
The same function without recursion:
double findfact(int a){
int sum = 1;
for(int i = a; i > 0; i--){
sum *= i;
}
return sum;
}
Same by the findpower function:
if b == 0 then return 1 else call findpower() with a, b-1 and multiply the return value of findpower() with a
So the last called findpower() will return 1 (b = 0)
The second last findpower() will return a * 1 (b = 1)
The third last findpower() will return a * a * 1 (b = 2)
so you can see findpower(a, 2) = a * a * 1 = a^2
Hope I could help you
Try to run below code, it will clear all your doubts (i have modified some access specifier and created main method)
public class SeriesSum
{
int x,n;
double sum;
SeriesSum(int xx,int nn)
{ x=xx;
n=nn;
sum=0.0;
}
double findfact(int a)
{ return (a<2)? 1:a*findfact(a-1);
}
double findpower(int a, int b)
{ return (b==0)? 1:a*findpower(a,b-1);
}
void calculate()
{
System.out.println("x ="+x);
System.out.println("n ="+n);
for(int i=2;i<=n;i+=2){
System.out.println(x+"^"+i+"/"+(i-1)+"!" +" = " +(findpower(x,i)+"/"+findfact(i-1)) );
//System.out.println(findpower(x,i)+"/"+findfact(i-1));
sum += findpower(x,i)/findfact(i-1);
}
}
void display()
{ System.out.println("sum="+ sum);
}
public static void main(String arg[])
{ SeriesSum obj = new SeriesSum(3,8);
obj.calculate();
obj.display();
}
}
// ----- output ----
x =3
n =8
3^2/1! = 9.0/1.0
3^4/3! = 81.0/6.0
3^6/5! = 729.0/120.0
3^8/7! = 6561.0/5040.0
sum=29.876785714285713
You can simplify the summation and get rid of power and factorial. Please notice:
The very first term is just x * x
If you know term item == x ** (2 * n) / (2 * n - 1)! the next one will be item * x * x / (2 * n) / (2 * n + 1).
Implementation:
private static double sum(double x, int count) {
double item = x * x; // First item
double result = item;
for (int i = 1; i <= count; ++i) {
// Next item from previous
item = item * x * x / (2 * i) / (2 * i +1);
result += item;
}
return result;
}
In the real world, you can notice that
sinh(x) = x/1! + x**3/3! + x**5/5! + ... + x**(2*n - 1) / (2*n - 1)! + ...
and your serie is nothing but
x * sinh(x) = x**2/1! + x**4 / 3! + ... + x**(2*n) / (2*n - 1)! + ...
So you can implement
private static double sum(double x) {
return x * (Math.exp(x) - Math.exp(-x)) / 2.0;
}

Efficiently computing a pair(base, exponent) representation of an integer n

I'm having trouble with desiging a method to express an integer n as an integer pair (base, exponent) such that n == base ^ exponent, for an assignment. Below is the contract for the method. #pre specifies what n has to be, #post defines what the output has to be.
/**
* Writes a number as a power with maximal exponent.
*
* #param n the number to 'powerize'
* #return power decomposition of {#code n} with maximal exponent
* #throws IllegalArgumentException if precondition violated
* #pre {#code 2 <= n}
* #post {#code n == power(\result) &&
* (\forall int b, int e;
* 2 <= b && 1 <= e && n == b ^ e;
* e <= \result.exponent)}
*/
public static Power powerize(int n){}
Where the class Power is just a Pair instance.
I already managed to solve this problem using a naive approach, in which I compute the value of the base and exponent by computing log(n) / log(b) with 2 <= b <= sqrt(n). But the assignment description says I have to produce an ellegant & efficient method and I couldn't find a way to compute this more efficiently.
After consulting some books I designed the following solution:
Input int n:
Let p1...pm be m unique primes.
Then we can express n as:
n = p1e1 x ... x pmem.
Then compute the gcd d of e1 ... em using the euclidean algorithm.
Then we express n as:
n = (p1e1/d x ... x pmem/d)d.
now we have:
b = p1e1/d x ... x pmem/d
e = d
return new Power(b, e)

Basic Prime Factorization with Exponents in Java

The Problem:
Any positive integer can be expressed as a unique product of prime numbers, also know as its prime factorization. For example:
60 = 2^2 * 3 * 5
Write a program to compute the prime factorization of a positive integer.
Input: A single integer, n, where n ≥ 2.
Output: A string with the format: “p^a * q^b * ...”, where p and q are primes, and a and b are exponents. If an exponent is 1, then it should be omitted.
I've got everything else down, I just need to find a way to put it into “p^a * q^b * ...” form.
Here is my code:
import java.util.Scanner;
public class PrimeFactorization {
public static void main(String[] args) {
// Input: A single integer, n, where n is greater than or equal to 2.
System.out.println("Please input an integer greater than or equal to two!");
System.out.println("This number will be factored.");
Scanner inputNum = new Scanner(System.in);
int toBFactored = inputNum.nextInt();
// If the input does not fit the requirements, ask again for an input.
while (toBFactored < 2) {
System.out.println("Please input an integer greater than or equal to two.");
toBFactored = inputNum.nextInt();
}
// Output: A string with the format: "p^a * q^b * ...", where p and q are
// primes, and a and b are exponents.
// Decide first if a number (testNum) is prime.
int primedecider = 0;
for (int testNum = 2; testNum < toBFactored; testNum ++) {
for (int factor = 2; factor < testNum; factor ++) {
if (testNum % factor != 0 || testNum == 2) {
// Do nothing if prime.
} else {
primedecider += 1;
// Add if composite.
}
}
// If testNum is prime, if primedecider = 0, test if testNum divides
// evenly into toBFactored.
while (primedecider == 0 && toBFactored % testNum == 0 {
System.out.print(testNum + " ");
toBFactored /= testNum;
}
}
System.out.print(toBFactored);
inputNum.close();
}
}
My output for 120 is "2 2 2 3 5". How do I make it into 2^3 * 3 * 5?
If instead of printing the factors with System.out.println,
if you put them in a list,
then these functions will format them in the way you described.
This is of course just one of the many ways of doing this.
private String formatFactors(List<Integer> factors) {
StringBuilder builder = new StringBuilder();
int prev = factors.get(0);
int power = 1;
int factor = prev;
for (int i = 1; i < factors.size(); ++i) {
factor = factors.get(i);
if (factor == prev) {
++power;
} else {
appendFactor(builder, prev, power);
prev = factor;
power = 1;
}
}
appendFactor(builder, factor, power);
return builder.substring(3);
}
private void appendFactor(StringBuilder builder, int factor, int power) {
builder.append(" * ").append(factor);
if (power > 1) {
builder.append("^").append(power);
}
}

Stuck on MIT's 6.005 Elements of Software Construction, cannot implement computePiInHex()

I am currently doing MIT's OCW 6.005 Elements of Software Construction for self- study.
I am on problem set 1.
The part I am currently stuck on is 1.d. It asks me to "Implement computePiInHex() in PiGenerator. Note that this function should
only return the fractional digits of Pi, and not the leading 3."
Here is what I have so far:
public class PiGenerator {
/**
* Returns precision hexadecimal digits of the fractional part of pi.
* Returns digits in most significant to least significant order.
*
* If precision < 0, return null.
*
* #param precision The number of digits after the decimal place to
* retrieve.
* #return precision digits of pi in hexadecimal.
*/
public static int[] computePiInHex(int precision) {
if(precision < 0) {
return null;
}
return new int[0];
}
/**
* Computes a^b mod m
*
* If a < 0, b < 0, or m < 0, return -1.
*
* #param a
* #param b
* #param m
* #return a^b mod m
*/
public static int powerMod(int a, int b, int m) {
if(a < 0 || b < 0 || m < 0)
return -1;
return (int) (Math.pow(a, b)) % m;
}
/**
* Computes the nth digit of Pi in base-16.
*
* If n < 0, return -1.
*
* #param n The digit of Pi to retrieve in base-16.
* #return The nth digit of Pi in base-16.
*/
public static int piDigit(int n) {
if (n < 0) return -1;
n -= 1;
double x = 4 * piTerm(1, n) - 2 * piTerm(4, n) -
piTerm(5, n) - piTerm(6, n);
x = x - Math.floor(x);
return (int)(x * 16);
}
private static double piTerm(int j, int n) {
// Calculate the left sum
double s = 0;
for (int k = 0; k <= n; ++k) {
int r = 8 * k + j;
s += powerMod(16, n-k, r) / (double) r;
s = s - Math.floor(s);
}
// Calculate the right sum
double t = 0;
int k = n+1;
// Keep iterating until t converges (stops changing)
while (true) {
int r = 8 * k + j;
double newt = t + Math.pow(16, n-k) / r;
if (t == newt) {
break;
} else {
t = newt;
}
++k;
}
return s+t;
}
}
The main method initiates a constant and then calls computePiInHex().
public static final int PI_PRECISION = 10000;
int [] piHexDigits = PiGenerator.computePiInHex(PI_PRECISION);
From my knowledge, the method piDigits() gets the nth digit of pi in base 16. So in computePiHex, should implement the BBP digit-extraction algorithm for Pi? Otherwise could someone point me in the right direction because I don't know what they're asking for in computePiInHex().
Try a different powermod algorithm.
For me this article helped a lot:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-005-elements-of-software-construction-fall-2011/assignments/MIT6_005F11_ps1.pdf
The actual algorithm I used is based on the pseudocode from Applied Cryptography by Bruce Schneier
https://en.m.wikipedia.org/wiki/Modular_exponentiation
function modular_pow(base, exponent, modulus)
if modulus = 1 then return 0
Assert :: (modulus - 1) * (modulus - 1) does not overflow base
result := 1
base := base mod modulus
while exponent > 0
if (exponent mod 2 == 1):
result := (result * base) mod modulus
exponent := exponent >> 1
base := (base * base) mod modulus
return result

Newton's method with specified digits of precision

I'm trying to write a function in Java that calculates the n-th root of a number. I'm using Newton's method for this. However, the user should be able to specify how many digits of precision they want. This is the part with which I'm having trouble, as my answer is often not entirely correct. The relevant code is here: http://pastebin.com/d3rdpLW8. How could I fix this code so that it always gives the answer to at least p digits of precision? (without doing more work than is necessary)
import java.util.Random;
public final class Compute {
private Compute() {
}
public static void main(String[] args) {
Random rand = new Random(1230);
for (int i = 0; i < 500000; i++) {
double k = rand.nextDouble()/100;
int n = (int)(rand.nextDouble() * 20) + 1;
int p = (int)(rand.nextDouble() * 10) + 1;
double math = n == 0 ? 1d : Math.pow(k, 1d / n);
double compute = Compute.root(n, k, p);
if(!String.format("%."+p+"f", math).equals(String.format("%."+p+"f", compute))) {
System.out.println(String.format("%."+p+"f", math));
System.out.println(String.format("%."+p+"f", compute));
System.out.println(math + " " + compute + " " + p);
}
}
}
/**
* Returns the n-th root of a positive double k, accurate to p decimal
* digits.
*
* #param n
* the degree of the root.
* #param k
* the number to be rooted.
* #param p
* the decimal digit precision.
* #return the n-th root of k
*/
public static double root(int n, double k, int p) {
double epsilon = pow(0.1, p+2);
double approx = estimate_root(n, k);
double approx_prev;
do {
approx_prev = approx;
// f(x) / f'(x) = (x^n - k) / (n * x^(n-1)) = (x - k/x^(n-1)) / n
approx -= (approx - k / pow(approx, n-1)) / n;
} while (abs(approx - approx_prev) > epsilon);
return approx;
}
private static double pow(double x, int y) {
if (y == 0)
return 1d;
if (y == 1)
return x;
double k = pow(x * x, y >> 1);
return (y & 1) == 0 ? k : k * x;
}
private static double abs(double x) {
return Double.longBitsToDouble((Double.doubleToLongBits(x) << 1) >>> 1);
}
private static double estimate_root(int n, double k) {
// Extract the exponent from k.
long exp = (Double.doubleToLongBits(k) & 0x7ff0000000000000L);
// Format the exponent properly.
int D = (int) ((exp >> 52) - 1023);
// Calculate and return 2^(D/n).
return Double.longBitsToDouble((D / n + 1023L) << 52);
}
}
Just iterate until the update is less than say, 0.0001, if you want a precision of 4 decimals.
That is, set your epsilon to Math.pow(10, -n) if you want n digits of precision.
Let's recall what the error analysis of Newton's method says. Basically, it gives us an error for the nth iteration as a function of the error of the n-1 th iteration.
So, how can we tell if the error is less than k? We can't, unless we know the error at e(0). And if we knew the error at e(0), we would just use that to find the correct answer.
What you can do is say "e(0) <= m". You can then find n such that e(n) <= k for your desired k. However, this requires knowing the maximal value of f'' in your radius, which is (in general) just as hard a problem as finding the x intercept.
What you're checking is if the error changes by less than k, which is a perfectly acceptable way to do it. But it's not checking if the error is less than k. As Axel and others have noted, there are many other root-approximation algorithms, some of which will yield easier error analysis, and if you really want this, you should use one of those.
You have a bug in your code. Your pow() method's last line should read
return (y & 1) == 1 ? k : k * x;
rather than
return (y & 1) == 0 ? k : k * x;

Categories