Dynamic Distribution Algorithm - java

I've been racking my brain all morning trying to come up with the following algorithm, this is especially frustrating because I'm sure that it's possible.
What I need is a class that has a function that returns boolean. It can be called any number of times and will return true XX% of the time. This CANNOT be a random distribution, for example:
If the ratio X is set to 0.6 and the function is called 100 times, we need to return exactly 60 true results. In which order "left overs" are used doesn't matter, for example: if the function was called 99 times it would be OK to return either 59 or 60 true values.
The trick here is that the ratio needs to be variable.
For some setup, I'm working in a multi threaded environment so I'm keeping my "hitNumber" variable in an AtomicLong in order to avoid synchronization issues.
Thanks!

If all you want is to maintain the overall percentage, just keep track of the percentage so far (probably as an explicit rational), and return true if you're under the target percentage, or false if you're over it.

Your criterion that it can't be random is pretty ill-defined. I suppose you mean that the quantity T/(T+F) is as close to the ratio as integer T and F will allow.
So you'll end up with something like this:
class TrueFalseGenerator {
final double ratio;
long nTrue, nFalse;
TrueFalseGenerator(double ratio) {
this.ratio = ratio;
nTrue = nFalse = 0;
}
synchronized boolean next() {
long den = nTrue + nFalse;
if (den == 0 || (double)nTrue / den < ratio) {
nTrue++;
return true;
} else {
nFalse++;
return false;
}
}
}

To build on Ben's answer, you can maintain static class variables to keep track of past function calls. Something like:
bool myFunc( float true_percentage ) {
count++; // where count and count_true are class static variables initialized to zero.
if ( float( count_true ) / count >= true_percentage )
return false;
count_true++;
return true;
}

This version uses only integer arithmetic and doesn't need any counter:
public class Distribution {
private int numerator;
private int denominator;
private int error;
public Distribution(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
public synchronized boolean next() {
error += numerator;
if (error >= denominator) {
error %= denominator;
return true;
}
return false;
}
}
Usage:
Distribution dist = new Distribution(6, 10); // 6 trues out of 10
dist.next(); // get next bool

//algorithm
//1st call randomize(x) from main with x as percentage
//this calls fischershuffle to shuffle the boolean array
//den calls to return bool are randomized with x trues and 100-x falses per 100 calls
class A{
public static int count=0;
public static boolean fill[]=new boolean[100];
public static void randomize(double x)
{
double totaltrue=x*100;
double totalfalse=100-totaltrue;
for(int i=0;i<100;i++)
{
if(totaltrue>0.00)
{
fill[i]=true;
totaltrue-=1.00;
}
else
{
fill[i]=false;
totalfalse-=1.00;
}
}
fill=fischershuffle(fill);
}
static boolean fischershuffle(boolean[] ar)
{
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
boolean a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
return ar;
}
public static boolean retunbool()
{
if(count<=100)
{
count++;
return fill[count];
}
else{
count=0;//resets after 100 for next 100 calls
}

Related

Find a number to the power of another number?

I am trying to write a function in java that finds the result of an operand raised to the power of another.
I can't use the pow function or any form of loop. What are any possible solutions? I tried "^" and that didn't work.
public static String raiseP(int op1, int op2){
int result = op1 ^ op2; //Doesn't Work
return result;
}
Would there be a way to do this using basic math?
I have written:
public static int pow(int x, int y, int n, int z){
if (y == n){
System.out.println(z);
return z;
}
else{
z = z*x;
n += 1;
pow(x,y,n,z);
return 0;
}
}
ex: pow(5,9,0,1) == 5^9
but am not allowed to use recursion.
Without being able to call Math.pow or using loops, the only other possibility is using recursion:
public int powerFunction(int base, int exponent) {
if(exponent < 0){ throw new IllegalArgumentException("unsupported negative pow"); }
if(exponent == 0){ return 1; }
else{
return base * powerFunction(base, exponent - 1);
}
}
Calling powerFunction(2, 3) will give you: 1 * 2 * 2 * 2 = 8
You could simply use that
pow(x,y) = exp(y*log(x))
which is also part of the implementation of the power function in the math library.
The recursion could help you:
public static int myPowerRec(int op1, int op2, int res) {
if (op2 == 0) {
return res;
}
else {
return (myPowerRec(op1, op2 - 1, op1 * res));
}
}
You will need to initialize res to 1 (myPowerRec(23, 2, 1) will give you 1 * 23 * 23).
This recursion is called tail recursion and will allow you to use this function without stack problem.
Be careful, you must check op2 value before.
Using a for loop:
public static int power(a, b) { // a ^ b
int p = 1;
for (int i = 1, i <= b; i++)
p *= a;
return p;
}

Java - Displaying Palindromic Primes

For my Java class, we have to write a program that displays all palindromic primes based on a number the user inputs. There are a couple other questions like this, but I need to do it without creating an array, or just typing in all of the palindromic primes.
My program works, and displays all primes, but the problem is that it displays ALL primes, not just the palindromic ones. I don't know where the error is, but I would appreciate any help I can get!
Thanks,
Ben
import java.util.Scanner;
public class PalindromePrimes {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int startingPoint = 1;
int startingPrime = 2;
final int printPerLine = 10;
IsItPrime(startingPrime);
IsItPalin(startingPrime);
System.out.println("Please Enter a Number: ");
int n = in.nextInt();
while (startingPoint <= n)
{
if (IsItPrime(startingPrime) && IsItPalin(startingPrime)) {
System.out.print(startingPrime + " ");
if (startingPoint % printPerLine == 0)
System.out.println();
startingPoint++;
}
startingPrime++;
}
}
public static boolean IsItPrime(int sPrime) {
if (sPrime == 2) {
return true;
}
for(int i = 2; 2 * i < sPrime; i++) {
if(sPrime % i == 0){
return false;
}
}
return true;
}
public static boolean IsItPalin(int sPrime) {
int p;
int reverse = 0;
while (sPrime > 0) {
p = sPrime % 10;
reverse = reverse * 10 + p;
sPrime = sPrime / 10;
}
if (sPrime == reverse) {
return false;
}
return true;
}
}
You could really improve both functions:
Some notes about IsItPrime:
Check first only for even numbers (you are doing this)
The for-loop could begin in 3 and increment by 2, to check only odd numbers, the even are checked in the previous point.
The for-loop only needs to check from 3 .. sqrt(N) + 1, if the number is not prime. It would be a prime if the number is less or equal to sqrt(N) and devides N.
Function IsItPrime improve:
public static boolean IsItPrime(int sPrime) {
if (sPrime % 2 == 0 && sPrime != 2) {
return false;
}
int sqrtPrime = (int)Math.sqrt(sPrime);
for (int i = 3; i <= sqrtPrime; i += 2) {
if (sPrime % i == 0) {
return false;
}
}
return true;
}
Some notes about IsItPalin:
The return result is swapped, when sPrime == reverse is palindrome, you must return true, not false.
The other problem is that in the function you are modifying the parameter sPrime in the while-loop, you need to save the original value for comparing in sPrime == reverse.
Function IsItPalin improved:
public static boolean IsItPalin(int sPrime) {
int sPrimeBackup = sPrime;
int reverse = 0;
while (sPrime > 0) {
reverse = reverse * 10 + sPrime % 10;
sPrime = sPrime / 10;
}
return (sPrimeBackup == reverse);
}
The problem is in the IsItPalin method. You are changing the value of sPrime, but then comparing sPrime to reverse. Make a copy of sPrime and compare the copy to reverse. Also, you should return true if they are equal, not false.
It looks like the problem is with your IsItPalin method. It's almost right, except for two problems.
The first problem is this:
if (sPrime == reverse) {
return false;
}
return true;
Whenever your prime number is equal to the reverse, you're returning false! This is the opposite of what we want.
The fix is to switch "true" and "false":
if (sPrime == reverse) {
return true;
}
return false;
We can actually simplify this into a single line:
return sPrime == reverse;
The second problem is with sPrime. Within your while loop, you're decreasing sPrime, and will only exit the loop when sPrime is equal to zero. That means that the only time sPrime will be equal to reverse is when you input the value of 0. To fix this, make a copy of sPrime at the top of the method and compare the copy to reverse.
The fixed version would look like this:
public static boolean IsItPalin(int sPrime) {
int copy = sPrime;
int reverse = 0;
while (sPrime > 0) {
int p = sPrime % 10;
reverse = reverse * 10 + p;
sPrime = sPrime / 10;
}
return copy == reverse;
}
This solution doesn't involve a loop, so it's probably faster
public static boolean isPaladrome(int mNumber) {
String numToString = String.valueOf(mNumber);
int sLength = numToString.length();
int midPoint = sLength / 2;
return (new StringBuilder(numToString.substring(0, midPoint)).reverse()
.toString()).equals(numToString.substring(sLength - midPoint));
}

Do I need this whole class to find out if the fraction is reduced or not?

What I have to do is take 2 random variables for a fraction, 1 to 1000, and check to see if they are in reduced terms already or not. I do this 1,000 times and keep track of whether it was or wasn't in reduced terms.
Here is the main class
import java.util.*;
public class ratio1 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int nonReducedCount = 0; //counts how many non reduced ratios there are
for(int i =1; i<=1000; i++){
Random rand = new Random();
int n = rand.nextInt(1000)+1; //random int creation
int m = rand.nextInt(1000)+1;
Ratio ratio = new Ratio(n,m);
if (ratio.getReduceCount() != 0 ){ // if the ratio was not already fully reduced
nonReducedCount++; // increase the count of non reduced ratios
}
}
int reducedCount = 1000 - nonReducedCount; //number of times the ratio was reduced already
double reducedRatio = reducedCount / nonReducedCount; //the ratio for reduced and not reduced
reducedRatio *= 6;
reducedRatio = Math.sqrt(reducedRatio);
System.out.println("pi is " + reducedRatio);
}
}
And here is the class I am not sure about. All I want from it is to determine whether or not the fraction is already in simplest form. When I currently try to run it, it is giving me an error; "Exception in thread "main" java.lang.StackOverflowError
at Ratio.gcd (Ratio.java:67)
at Ratio.gcd (Ratio.java:66)"
public class Ratio{
protected int numerator; // numerator of ratio
protected int denominator; //denominator of ratio
public int reduceCount = 0; //counts how many times the reducer goes
public Ratio(int top, int bottom)
//pre: bottom !=0
//post: constructs a ratio equivalent to top::bottom
{
numerator = top;
denominator = bottom;
reduce();
}
public int getNumerator()
//post: return the numerator of the fraction
{
return numerator;
}
public int getDenominator()
//post: return the denominator of the fraction
{
return denominator;
}
public double getValue()
//post: return the double equivalent of the ratio
{
return (double)numerator/(double)denominator;
}
public int getReduceCount()
//post: returns the reduceCount
{
return reduceCount;
}
public Ratio add(Ratio other)
//pre: other is nonnull
//post: return new fraction--the sum of this and other
{
return new Ratio(this.numerator*other.denominator+this.denominator*other.numerator,this.denominator*other.denominator);
}
protected void reduce()
//post: numerator and denominator are set so that the greatest common divisor of the numerator and demoninator is 1
{
int divisor = gcd(numerator, denominator);
if(denominator < 0) divisor = -divisor;
numerator /= divisor;
denominator /= divisor;
reduceCount++;
}
protected static int gcd(int a, int b)
//post: computes the greatest integer value that divides a and b
{
if (a<0) return gcd(-a,b);
if (a==0){
if(b==0) return 1;
else return b;
}
if (b>a) return gcd(b,a);
return gcd(b%a,a);
}
public String toString()
//post:returns a string that represents this fraction.
{
return getNumerator()+"/"+getDenominator();
}
}
Here are the lines of the error in the Ratio class;
if (b>a) return gcd(b,a);
return gcd(b%a,a);
A fraction is reducible if its GCD is greater than 1. You can compute the GCD with the static method given in Ratio, so you could instead use:
...
int n = rand.nextInt(1000)+1;
int m = rand.nextInt(1000)+1;
if(Ratio.gcd(n,m) == 1) {
nonReducedCount++;
}
This saves you from instantiating a new Ratio instance.
If that method doesn't work for you, you can always use your own GCD calculator. This one is recursive too and similar to the one in Ratio:
public static int gcd(int a, int b) { return b==0 ? a : gcd(b,a%b); }
You could Google it for non-recursive methods if the StackOverflowError is still a problem.

Recursive Exponent Method

public static int exponent(int baseNum) {
int temp = baseNum *= baseNum;
return temp * exponent(baseNum);
}
Right now the method above does n * n into infinity if I debug it, so it still works but I need this recursive method to stop after 10 times because my instructor requires us to find the exponent given a power of 10.
The method must have only one parameter, here's some examples of calling exponent:
System.out.println ("The power of 10 in " + n + " is " +
exponent(n));
So output should be:
The power of 10 in 2 is 1024
OR
The power of 10 in 5 is 9765625
Do something like
public static int exp(int pow, int num) {
if (pow < 1)
return 1;
else
return num * exp(pow-1, num) ;
}
public static void main (String [] args) {
System.out.println (exp (10, 5));
}
and do not forget the base case (i.e a condition) which tells when to stop recursion and pop the values from the stack.
Create an auxiliary method to do the recursion. It should have two arguments: the base and the exponent. Call it with a value of 10 for the exponent and have it recurse with (exponent-1). The base case is exponent == 0, in which case it should return 1. (You can also use exponent == 1 as a base case, in which case it should return the base.)
The following is what my instructor, Professor Penn Wu, provided in his lecture note.
public class Exp
{
public static int exponent(int a, int n)
{
if (n==0) { return 1; } // base
else // recursion
{
a *= exponent(a, n-1);
return a;
}
}
public static void main(String[] args)
{
System.out.print(exponent(2, 10));
}
}
Shouldn't it have 2 parameter and handle exit condition like below?
public static int exponent(int baseNum, int power) {
if(power == 0){
return 1;
}else{
return baseNum * exponent(baseNum, power-1);
}
}
For recursion function, we need to :
check stopping condition (i.e. when exp is 0, return 1)
call itself with adjusted condition (i.e. base * base^(n-1) )
Here is the code.
public class Test
{
public static int exponent(int baseNum, int exp)
{
if (exp<=0)
return 1;
return baseNum * exponent(baseNum, --exp);
}
public static void main(String a[])
{
int base=2;
int exp =10;
System.out.println("The power of "+exp+" in "+base+" is "+exponent(base,exp));
}
}
Don't forget , for each recursive function , you need a base case. A stop condition`
static double r2(float base, int n)
{
if (n<=0) return 1;
return base*r2(base,n-1);
}
I came here accidentally, and I think one could do better, as one would figure out easily that if exp is even then x^2n = x^n * x^n = (x^2)^n, so rather than computing n^2-1 recursions, you can just compute xx and then call pow(x,n) having n recursions and a product. If instead the power is odd, then we just do xpow(x, n-1) and make the power even again. But, as soon as now n-1 is even, we can directly write xpow(xx, (n-1)/2) adding an extra product and using the same code as for the even exponent.
int pow_( int base, unsigned int exp ) {
if( exp == 0 )
return 1;
if( exp & 0x01 ) {
return base * pow_( base*base, (exp-1)/2 );
}
return pow_( base*base, exp/2 );
}

Project Euler #3 Java Solution Problem

class eulerThree {
public static void main(String[] args) {
double x = 600851475143d;
for (double z = 2; z*z <= x; z++) {
if (x%z == 0) {
System.out.println(z + "PRIME FACTOR");
}
}
}
}
and the output is:
71.0
839.0
1471.0
6857.0
59569.0
104441.0
486847.0
So, I assume 486847 is the largest prime factor of x, but project euler says otherwise. I don't see a problem in my code or my math, so I'm pretty confused. Can you see anything I can't?
Firstly, you have to use an accurate arithmetic means. Others have suggested using BigInteger. You can do this. To me, it feels a bit like cheating (this will be more important for later problems that deal with much larger integers) so the more fun way (imho) is to write the necessary arbitrary precision operations yourself.
Second, 600851475143 is small enough to be done accurate with a long, which will be much faster.
Third, your loop isn't correctly checking for prime factors. You're just checking odd numbers. This is a barebones (incomplete) solution:
long num = 600851475143L;
List<Long> factors = new ArrayList<Long>(); // or use a Set
if (num & 1 == 0) {
factors.add(2L);
}
for (long i=3; i*i<=num; i+=2) {
// first check i is prime
// if i is prime check if it is a factor of num
}
Checking if something is prime has differing levels of implementation. The most naive:
public boolean isPrime(long num) {
for (long i=2; i<=num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
Of course that does all sorts of unnecessary checking. As you've already determined you only need to check numbers up to sqrt(n) and you can eliminate even numbers (other than 2):
public boolean isPrime(long num) {
if (num & 1 == 0) {
return false; // checks divisibility by 2
}
for (long i=3; i*i<=num; i+=2) {
if (num % i == 0) {
return false;
}
}
return true;
}
But you can do better than this as well. Another optimization is that you only need to check a number by prime numbers within that range. The prime factors of 63 are 3 and 7. If a number isn't divisible by 3 or 7 then it by definition won't be divisible by 63.
So what you want to do is build up probably a Set<Long> or prime numbers until the square is equal to or higher than your target number. Then just check this series of numbers for divisibility into the target.
double is inherently inaccurate for large values and should never be used for these type of number operations. The right class to use is BigInteger, which allows arbitrarily large integral values to be represented precisely. See this wikipedia article for a description on what floating point data types are and are not.
First, use BigInteger or long rather than double. Double isn't exact, and as you get to later problems, it won't be correct at all.
Second, what you're printing is factors, not prime factors.
This will work in your case:
for (double z = 2; z <= x; z++) {
if (x%z == 0) {
while( x%z == 0)
x = x/z
System.out.println(z + "PRIME FACTOR");
}
}
Also, Project Euler gives you sample input and output. Use that, since your code doesn't output values that match the example they give in the problem.
Two things:
Don't use double, the bigger the numbers the less precision it has. Instead you can use BigInteger to store arbitrarily large integers, or in this case a simple long will suffice.
You need to divide by the prime factor after you find it, otherwise you'll find all factors not just prime factors. Something like this:
if (x % z == 0) {
System.out.println(z + "PRIME FACTOR");
x /= z;
z -= 1; // Might be present multiple times, try it again
}
public class Prime {
public static void main(String[] args) {
double out = 0;
double m = 600851475143d;
for (double n = 3; n < m; n += 2) {
while (m % n == 0) {
out = n;
m = m / n;
}
}
System.out.println("" + ((m == 1)?out:m));
}
}
See the program. And you'll understand the algorithm. This is very easy and very fast. And return the correct answer 6857.
import java.util.Scanner;
class Primefactor
{
public static void main(String args[])
{
Scanner get=new Scanner(System.in);
System.out.println("Enter a number");
long number=get.nextLong();
int count=0;
long input=number;
for(long i=number;i>=1;number--)
{
for(long j=number;j>=1;j--)
{
if(i%j==0)
{
count++;
}
if(count==2)
{
if(input%j==0)
{
System.out.println(j);
}
}
}
}
}
}
This is to see largest primefactor of any number within the datatype limit.
public static void largestPrimeNo(long lim)
{
long newNum = lim;
long largestFact = 0;
int counter = 2;
while( counter * counter <= newNum )
{
if(newNum % counter == 0)
{
newNum = newNum / counter;
largestFact = counter;
}else{
counter++;
}
}
if(newNum > largestFact)
{
largestFact=newNum;
}
System.out.println(largestFact);
}
}
as Prime no is work on the principle that Any integer greater than 1 is either a prime number, or can be written as a unique product of prime numbers.So we can easily use above program.In this program we divide the long no,and find its prime factor
package findlaragestprimefactor;
public class FindLaragestPrimeFactor{
boolean isPrime(long number) {
for (long divider = 2; divider <= number / 2; divider++) {
if (number % divider == 0) {
return false;
}
}
return true;
}
void calculateLargestPrimeFactor() {
long largestPrimeFactor = 0;
long x = 600851475143L;
for(long factor = 3 ; factor <= x/2 ; factor = factor + 2){
if(x%factor==0 & factor>largestPrimeFactor & isPrime(factor)){
largestPrimeFactor = factor;
}
}
System.out.println(largestPrimeFactor);
}
public static void main(String[] args) {
MyProject m = new MyProject();
m.calculateLargestPrimeFactor();
}
}
long tNum=600851475143L;
ArrayList<Integer> primeNum=new ArrayList();
System.out.println(10086647/1471);
for(int i=2;i<=tNum;i++) {
if(tNum%i==0) {
primeNum.add(i);
tNum=tNum/i;
}
}
System.out.println(primeNum);

Categories