Hogy-Bear

Q5

Feb 8th, 2018
252
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.44 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int StarAndTriangleNumbers(int max); //protype
  4.  
  5. int main(int argc, char const *argv[]) {
  6.  
  7.   StarAndTriangleNumbers(10);
  8.  
  9.   return 0;
  10. }
  11.  
  12. int StarAndTriangleNumbers(int max){
  13.  
  14.   int maxTriangles = max*10; //we need more triangle numbers than star numbers to check against 10 isnt specific would work with anything bigger than 5 probably
  15.   int starNumbers[max]; //create an array to hold starnumbers
  16.   int triangleNumbers[maxTriangles]; //creates an array to hold triangle numbers
  17.  
  18.   //create star numbers array
  19.   for (int i = 1; i <= max; i++){
  20.     starNumbers[i] = ( ( (6 * i) * ( i - 1) ) + 1 );
  21.     // printf("star number %d is %d\n",i, starNumbers[i]);
  22.   }
  23.  
  24.   //create triangle numbers array
  25.   for (int i = 1; i <= maxTriangles; i++){
  26.     int num = 0;
  27.     for (int j = 1; j <= i; j++){
  28.       num += j;
  29.     }
  30.     triangleNumbers[i] = num;
  31.     // printf("triangle number %d is %d\n", i, triangleNumbers[i]);
  32.   }
  33.  
  34.   int matches[max]; //hold indcies of which ever star number matches a triangle numbers
  35.   int y = 0;
  36.  
  37.   //simple binary search algorithm.
  38.   for (int i = 1; i <= max; i++){
  39.     for (int j = 1; j < maxTriangles; j++){
  40.       if(starNumbers[i] == triangleNumbers[j]){
  41.         matches[y] = i;
  42.         y++;
  43.       }
  44.     }
  45.   }
  46.  
  47.   //print out the numbers
  48.   for (int i = 0; i < (y - 1); i++) {
  49.     printf("%d,", starNumbers[matches[i]]);
  50.   }
  51.   printf("%d\n", starNumbers[matches[y-1]]);
  52.  
  53.   return 0;
  54.  
  55. }
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment