Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Code for checking for pythogrean triples.

  1. Jun 4, 2007 #1
    i was asked to write a code that search for pythogrean triples, my fault in my code is that i don't know where to write the codnition that a<b<c, cause as of now runs duplicates of pyhtogrean's triples.
    here's the code:
    Code (Text):

    main()
    {
      int n,max,a,b,c;
     printf("insert the degree you wish to check for n-th pythogrean triplets\n");
     scanf("%d", &n);
     printf("insert the maximal number you want to check for\n");
     scanf("%d", &max);
     if(max>2){
       
       for(a=1;a<=max;a++)
         {
           for(b=2;b<=max;b++)
             {
       for(c=3;c<=max;c++)
         {
           if((pow(a,n)+pow(b,n)==pow(c,n))&& gcd(a,b)==1){
             f++;
             printf("the triplet is: %d, %d, %d \n", a,b,c);
           
           
         }
             }
         }
     }
    }
     
    any hints as to where to place this condition?
     
  2. jcsd
  3. Jun 4, 2007 #2
    In the for loops, forsooth. If b should be greater than a, why not run the for loop for b=a+1 to the max, and likewise for c.
     
  4. Jun 7, 2007 #3

    CRGreathouse

    User Avatar
    Science Advisor
    Homework Helper

    Yes, this will make the code perhaps 4 times faster in addition to removing duplicates.

    To make it faster yet (and ward off potential floating-point problems) you should multiply rather than power:

    Code (Text):
    main()
    {
      int n,max,a,b,c;
     printf("insert the degree you wish to check for n-th pythogrean triplets\n");
     scanf("%d", &n);
     printf("insert the maximal number you want to check for\n");
     scanf("%d", &max);
     if(n > 2) {
       /* There are no solutions by the Fermat-Wiles Theorem */
     }
     elseif(max>2 && n == 2){
       for(a=1;a<max;a++) {
           for(b=a+1;b<max;b++) {
             for(c=b+1;c<=max;c++) {
               if(a*a+b*b==c*c && gcd(a,b)==1) {
                 f++;
                 printf("the triplet is: %d, %d, %d \n", a,b,c);
               }
             }
           }
       }
    }
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Code for checking for pythogrean triples.
  1. Error in code (Replies: 4)

  2. Examples of code (Replies: 2)

  3. Code Blocks (Replies: 2)

  4. The Source Code! (Replies: 15)

Loading...