Pythagorean triples/Java/Brute force primitives: Difference between revisions

From Rosetta Code
Content added Content deleted
(Fursther optimization by skipping more a,b pair candidates (noted in the comments), rm runtime calculations)
m (Somewhere in there I got rid of the need for 12 as a BigInteger, reformat)
 
(11 intermediate revisions by the same user not shown)
Line 1:
{{works with|Java|1.5+}}
This version brute forces primitive triple candidates and then scales them to find the rest (under the perimeter limit of course). Since it only finds the primitives mathematically it can optimize its candidates based on some of the properties [[wp:Pythagorean_triple#Elementary_properties_of_primitive_Pythagorean_triples|here]] -- namely that a and b have opposite evenness, only one of a and b is divisible by 3, only one of a and b is divisible by 4, c is always odd, and that a<sup>2</sup> + b<sup>2</sup> must be a perfect square (which [[wp:Square_number#Properties|don't ever end in 2, 3, 7, or 8]]). NotablyAfter using those rules to eliminate candidates for a,b pairs, it doesn'tchecks usethat a GCDand functionb toare checkcoprime. forSince primitivesmany (<code>BigInteger.gcd()</code>a,b usespair thecandidates binaryhave GCDalready algorithmbeen eliminated, [[wp:Computational_complexity_of_mathematical_operations#Number_theory|whichthis ischeck O(n<sup>2</sup>)]])actually speeds things up a little bit by letting the program skip some c loops. For a perimeter limit of 1000, it is about 45 times faster than [[Pythagorean triples#Java|the other brute force version]]. For a perimeter limit of 10000, it is about 817 times faster. It also does not markmarks the primitives.
 
It defines a <code>Triple</code> class which is comparable so it can be placed in a <code>SetTreeSet</code> for easy sorting and to remove duplicates (e.g.the thisGCD algorithmcheck findsshould [15,remove 20duplicates, 25] as a primitive candidate afterbut it's hadnice alreadyto been added by scaling [3, 4,make 5]sure). It also can scale itself by an integer factor.
 
Note: this implementation also keeps all triples in memory. Be mindful of large perimeter limits.
Line 8:
import java.util.Set;
import java.util.TreeSet;
import static java.math.BigInteger.ONE;
 
import static java.math.BigInteger.ONE*;
public class PythTrip2{
 
public static final BigInteger TWO = BigInteger.valueOf(2),
public class PythTrip2PythTrip{
B7 = BigInteger.valueOf(7), //B7...B191 are used for skipping non-square "a^2 + b^2"s
private static final BigInteger B31TWO = BigInteger.valueOf(312),
B3 = BigInteger.valueOf(3), B127B4 = BigInteger.valueOf(1274),
B7 = BigInteger.valueOf(7), B191B31 = BigInteger.valueOf(19131);,
private static B127 = BigInteger.valueOf(127), LIMITB191 = BigInteger.valueOf(100191);
//change this to whatever perimeter limit you want;the RAM's the limit
publicprivate static classBigInteger TripleLIMIT implements= Comparable<Triple>{BigInteger.valueOf(100);
 
BigInteger a, b, c, peri;
public static class Triple implements Comparable<Triple>{
public Triple(BigInteger a, BigInteger b, BigInteger c), {peri;
boolean this.a = aprim;
 
this.b = b;
public Triple(BigInteger a, BigInteger b, BigInteger c, boolean prim){
this.c = c;
perithis.a = a.add(b).add(c);
}this.b = b;
this.c = c;
publicperi Triple= scalea.add(long kb).add(c){;
BigIntegerthis.prim a,= b, c, periprim;
return new Triple(a.multiply(BigInteger.valueOf(k)),
}
b.multiply(BigInteger.valueOf(k)),
 
c.multiply(BigInteger.valueOf(k)));
public Triple scale(long }k){
return new Triple(a.multiply(BigInteger.valueOf(k)), b
b.multiply(BigInteger.valueOf(k)), c.multiply(BigInteger
@Override
public boolean equals(Object obj .valueOf(k)), {prim && k == 1);
}
if(obj.getClass() != this.getClass()) return false;
 
Triple trip = (Triple)obj;
@Override
return a.equals(trip.a) && b.equals(trip.b) && c.equals(trip.c);
public boolean equals(Object }obj){
if(obj.getClass() != this.getClass()) return false;
@Override return false;
publicTriple inttrip = compareTo(Triple o) {obj;
return //sort by a,.equals(trip.a) then&& b,.equals(trip.b) then&& c.equals(trip.c);
}
if(!a.equals(o.a)) return a.compareTo(o.a);
 
if(!b.equals(o.b)) return b.compareTo(o.b);
@Override
if(!c.equals(o.c)) return c.compareTo(o.c);
public int compareTo(Triple return 0;o){
}if(!a.equals(o.a))
return a.compareTo(o.a);
@Overrideif(!b.equals(o.b))
public String toString return b.compareTo(o.b){;
return a + ", " + b + ", " + if(!c;.equals(o.c))
} return c.compareTo(o.c);
} return 0;
}
 
private static Set<Triple> trips = new TreeSet<Triple>();
public String toString(){
return a + ", " + b + ", " + c + (prim ? " primitive" : "");
public static void addAllScales(Triple trip){
long k = 1;}
}
Triple tripCopy = new Triple(trip.a, trip.b, trip.c);
 
while(tripCopy.peri.compareTo(LIMIT) < 0){
private static Set<Triple> trips = new TreeSet<Triple>();
trips.add(tripCopy);
 
tripCopy = trip.scale(k++);
public static void addAllScales(Triple trip){
}
} long k = 2;
Triple tripCopy = new Triple(trip.a, trip.b, trip.cscale(k++);
public static void main(String[] args){
while(tripCopy.peri.compareTo(LIMIT) <= 0){
trips.add(tripCopy);
tripCopy = trip.scale(k++);
}
}
 
public static void main(String[] args){
long primCount = 0;
long start = System.currentTimeMillis();
 
BigInteger peri2 = LIMIT.divide(BigIntegerTWO), peri3 = LIMIT.valueOfdivide(2B3)),;
//change this to whatever perimeter limit you want;the RAM's the limit
BigInteger peri2 = LIMIT.divide(BigInteger.valueOf(2)),
peri3 = LIMIT.divide(BigInteger.valueOf(3));
 
for(BigInteger a = ONEB3; a.compareTo(peri3) < 0; a = a.add(ONE)){
BigInteger aa = a.multiply(a);
boolean amod3 = a.mod(B3).equals(ZERO);
boolean amod4 = a.mod(B4).equals(ZERO);
 
//b is the opposite evenness of a so increment by 2
for(BigInteger b = a.add(ONE); b.compareTo(peri2) < 0; b = b
b.compareTo(peri2) < 0; b = b.add(TWO)){
BigInteger//skip bbif =both or neither of a and b.multiply(b); are divisible by 3 and 4
//if(amod3 a^2 +== b^2 is not a perfect square then don't even test for c's.mod(B3).equals(ZERO)
BigInteger aabb || amod4 == aab.addmod(bbB4).equals(ZERO));
if((aabb.and(B7).intValue() != 1) && continue;
//if a^2+b^2 isn't (aabb.and(B31).intValue()a !=perfect 4)square, &&don't even test for c's
BigInteger aabb = (aabbaa.andadd(B127)b.intValuemultiply(b) != 16) && ;
if((aabb.and(B191B7).intValue() != 01)) continue;
break;&& (aabb.and(B31).intValue() != 4)
&& (aabb.and(B127).intValue() != 16)
&& c(aabb.multiplyand(BigIntegerB191).valueOfintValue(k) != 0));
this.b = bcontinue;
if(!ba.equalsgcd(o.b)) return b.compareToequals(o.bONE));
this.c = ccontinue;
BigInteger ab = a.add(b);
 
// c is always odd for primitives so if b is odd start at b+2
for(BigInteger c = b.add(b.and(ONE).equals(ONE)? TWO:ONE);
// otherwise c.compareTo(peri2) < 0; c = c.add(TWO)){b+1
for(BigInteger c = b.add(b.testBit(0) //if? a+b+cZERO >: periLimitONE); c
if(ab.add(c) .compareTo(LIMITperi2) >< 0; c = c.add(TWO)){
 
break;
}// if a+b+c > periLimit
if(!aab.equalsadd(o.ac)) return a.compareTo(o.aLIMIT) > 0) break;
 
int compare = aabb.compareTo(c.multiply(c));
// if a^2 + b^2 != c^2
if(compare < 0){
break;
}else if (compare == 0){
Triple prim = new Triple(a, b, c, true);
if(trips.add(prim)){ //if it's new
primCount++; //count it
addAllScales(prim); //add its scales
}
}
Line 110 ⟶ 123:
}
}
for(Triple trip : trips){
System.out.println(trip);
}
System.out.println("Runtime: " + (System.currentTimeMillis() - start));
System.out.println("Up to a perimeter of " + LIMIT + ", there are "
+ trips.size() + " triples, of which " + primCount + " are primitive.");
+ " Tripleare trip = (Tripleprimitive.")obj;
}
}</lang>
Output:
<pre>3, 4, 5 primitive
5, 12, 13 primitive
6, 8, 10
7, 24, 25 primitive
8, 15, 17 primitive
9, 12, 15
9, 40, 41 primitive
10, 24, 26
12, 16, 20
12, 35, 37 primitive
15, 20, 25
15, 36, 39
16, 30, 34
18, 24, 30
20, 21, 29 primitive
21, 28, 35
24, 32, 40

Latest revision as of 20:45, 20 December 2011

Works with: Java version 1.5+

This version brute forces primitive triple candidates and then scales them to find the rest (under the perimeter limit of course). Since it only finds the primitives mathematically it can optimize its candidates based on some of the properties here -- namely that a and b have opposite evenness, only one of a and b is divisible by 3, only one of a and b is divisible by 4, c is always odd, and that a2 + b2 must be a perfect square (which don't ever end in 2, 3, 7, or 8). After using those rules to eliminate candidates for a,b pairs, it checks that a and b are coprime. Since many a,b pair candidates have already been eliminated, this check actually speeds things up a little bit by letting the program skip some c loops. For a perimeter limit of 1000, it is about 5 times faster than the other brute force version. For a perimeter limit of 10000, it is about 17 times faster. It also marks the primitives.

It defines a Triple class which is comparable so it can be placed in a TreeSet for easy sorting and to remove duplicates (the GCD check should remove duplicates, but it's nice to make sure). It also can scale itself by an integer factor.

Note: this implementation also keeps all triples in memory. Be mindful of large perimeter limits. <lang java5>import java.math.BigInteger; import java.util.Set; import java.util.TreeSet;

import static java.math.BigInteger.*;

public class PythTrip{

   private static final BigInteger TWO = BigInteger.valueOf(2),
           B3 = BigInteger.valueOf(3), B4 = BigInteger.valueOf(4),
           B7 = BigInteger.valueOf(7), B31 = BigInteger.valueOf(31),
           B127 = BigInteger.valueOf(127), B191 = BigInteger.valueOf(191);
   //change this to whatever perimeter limit you want;the RAM's the limit
   private static BigInteger LIMIT = BigInteger.valueOf(100);
   public static class Triple implements Comparable<Triple>{
       BigInteger a, b, c, peri;
       boolean prim;
       public Triple(BigInteger a, BigInteger b, BigInteger c, boolean prim){
           this.a = a;
           this.b = b;
           this.c = c;
           peri = a.add(b).add(c);
           this.prim = prim;
       }
       public Triple scale(long k){
           return new Triple(a.multiply(BigInteger.valueOf(k)), b
                   .multiply(BigInteger.valueOf(k)), c.multiply(BigInteger
                   .valueOf(k)), prim && k == 1);
       }
       @Override
       public boolean equals(Object obj){
           if(obj.getClass() != this.getClass())
               return false;
           Triple trip = (Triple) obj;
           return a.equals(trip.a) && b.equals(trip.b) && c.equals(trip.c);
       }
       @Override
       public int compareTo(Triple o){
           if(!a.equals(o.a))
               return a.compareTo(o.a);
           if(!b.equals(o.b))
               return b.compareTo(o.b);
           if(!c.equals(o.c))
               return c.compareTo(o.c);
           return 0;
       }
       public String toString(){
           return a + ", " + b + ", " + c + (prim ? " primitive" : "");
       }
   }
   private static Set<Triple> trips = new TreeSet<Triple>();
   public static void addAllScales(Triple trip){
       long k = 2;
       Triple tripCopy = trip.scale(k++);
       while(tripCopy.peri.compareTo(LIMIT) <= 0){
           trips.add(tripCopy);
           tripCopy = trip.scale(k++);
       }
   }
   public static void main(String[] args){
       long primCount = 0;
       long start = System.currentTimeMillis();
       BigInteger peri2 = LIMIT.divide(TWO), peri3 = LIMIT.divide(B3);
       for(BigInteger a = B3; a.compareTo(peri3) < 0; a = a.add(ONE)){
           BigInteger aa = a.multiply(a);
           boolean amod3 = a.mod(B3).equals(ZERO);
           boolean amod4 = a.mod(B4).equals(ZERO);
           //b is the opposite evenness of a so increment by 2
           for(BigInteger b = a.add(ONE); b.compareTo(peri2) < 0; b = b
                   .add(TWO)){
               //skip if both or neither of a and b are divisible by 3 and 4
               if(amod3 == b.mod(B3).equals(ZERO)
                       || amod4 == b.mod(B4).equals(ZERO))
                   continue;
               //if a^2+b^2 isn't a perfect square, don't even test for c's
               BigInteger aabb = aa.add(b.multiply(b));
               if((aabb.and(B7).intValue() != 1)
                       && (aabb.and(B31).intValue() != 4)
                       && (aabb.and(B127).intValue() != 16)
                       && (aabb.and(B191).intValue() != 0))
                   continue;
               if(!a.gcd(b).equals(ONE))
                   continue;
               BigInteger ab = a.add(b);
               // c is always odd for primitives so if b is odd start at b+2
               // otherwise b+1
               for(BigInteger c = b.add(b.testBit(0) ? ZERO : ONE); c
                       .compareTo(peri2) < 0; c = c.add(TWO)){
                   // if a+b+c > periLimit
                   if(ab.add(c).compareTo(LIMIT) > 0) break;
                   int compare = aabb.compareTo(c.multiply(c));
                   // if a^2 + b^2 != c^2
                   if(compare < 0){
                       break;
                   }else if(compare == 0){
                       Triple prim = new Triple(a, b, c, true);
                       if(trips.add(prim)){
                           primCount++;
                           addAllScales(prim);
                       }
                   }
               }
           }
       }
       for(Triple trip : trips){
           System.out.println(trip);
       }
       System.out.println("Runtime: " + (System.currentTimeMillis() - start));
       System.out.println("Up to a perimeter of " + LIMIT + ", there are "
               + trips.size() + " triples, of which " + primCount
               + " are primitive.");
   }

}</lang> Output:

3, 4, 5 primitive
5, 12, 13 primitive
6, 8, 10
7, 24, 25 primitive
8, 15, 17 primitive
9, 12, 15
9, 40, 41 primitive
10, 24, 26
12, 16, 20
12, 35, 37 primitive
15, 20, 25
15, 36, 39
16, 30, 34
18, 24, 30
20, 21, 29 primitive
21, 28, 35
24, 32, 40
Up to a perimeter of 100, there are 17 triples, of which 7 are primitive.