banovski

Project Euler, Problem #12, C

Feb 19th, 2022 (edited)
1,335
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.56 KB | None | 0 0
  1. /* The sequence of triangle numbers is generated by adding the natural
  2.  * numbers. So the 7th triangle number would be
  3.  * 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3,
  4.  * 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the
  5.  * first seven triangle numbers: 1: 1; 3: 1, 3; 6: 1, 2, 3, 6; 10:
  6.  * 1, 2, 5, 10; 15: 1, 3, 5, 15; 21: 1, 3, 7, 21; 28:
  7.  * 1, 2, 4, 7, 14, 28 We can see that 28 is the first triangle number
  8.  * to have over five divisors. What is the value of the first triangle
  9.  * number to have over five hundred divisors? */
  10.  
  11. #include <stdio.h>
  12. #include <math.h>
  13.  
  14. int main()
  15. {
  16.      /* counter */
  17.      int cntr = 2;
  18.      /* current triangle number */
  19.      int ctn = 1;
  20.      /* divisions number */
  21.      int dn = 0;
  22.      /* maximum divisor */
  23.      int md;
  24.      /* divisor */
  25.      int d;
  26.  
  27.      while(1)
  28.      {
  29.           ctn = ctn + cntr;
  30.           md = (int)sqrt((double)ctn);
  31.  
  32.           if(ctn % 2 == 0)
  33.           {
  34.                for(d = 1; d <= md; d++)
  35.                     if(ctn % d == 0)
  36.                          dn += 2;
  37.           }
  38.           else
  39.           {
  40.                for(d = 1; d <= md; d += 2)
  41.                     if(ctn % d == 0)
  42.                          dn += 2;
  43.           }
  44.  
  45.           if(md == (int)ceil(sqrt((double)ctn)))
  46.                dn--;
  47.                    
  48.           if(dn > 500)
  49.                break;
  50.          
  51.           dn = 0;
  52.           cntr++;
  53.      }
  54.      printf("%d\n", ctn);
  55.      return(0);
  56. }
  57.  
  58. /* 76576500
  59.  *
  60.  * real 0m0,368s
  61.  * user 0m0,368s
  62.  * sys  0m0,000s */
  63.  
Add Comment
Please, Sign In to add comment