Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all combinations of a^2 + b^2 in C

Tags:

c

I'm trying to find all combinations of x, where x = a^2 + b^2, and x is between 100 and 999.

So far i've got:

#include <stdio.h>
#include <stdlib.h>

#define MAX 31 // given that 31^2 = 961

int main(){
    int i = 0;
    int poss_n[] = {0};

    for (int a=0; a <= MAX; a++){
        for (int b=0; b <= MAX; b++){
            if (a*a + b*b >= 100 && a*a + b*b <= 999){ 
                poss_n[i] = a*a + b*b;
                printf("%i\n", poss_n[i]);
                i++;
            }
        }
    }
}

However it's giving only partially correct output, and also prematurely ends with segmentation fault 11:

100 1380405074 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 784 841 900 961 101 122 145 170 197 226 257 290 325 362 401 442 485 530 577 626 677 730 785 842 901 962 104 125 148 173 200 229 260 293 328 365 404 445 488 533 580 629 680 733 788 845 904 965 109 130 153 178 205 234 265 298 333 370 409 450 493 538 585 634 685 738 793 850 909 970 116 137 160 185 212 241 272 305 340 377 416 457 500 545 592 641 692 745 800 857 916 977 106 125 146 169 194 221 250 281 314 349 386 425 466 509 554 601 650 701 754 809 866 925 986 100 117 136 157 180 205 232 261 292 325 360 397 436 477 520 Segmentation fault: 11

What modifications should I make to my code?

UPDATE

Other than the the array issue, is there anything else wrong with my code? for instance it's still printing 100 as the first value which doesn't appear to be any combination of a^2 + b^2, even when b = 0.

UPDATE 2

Never mind, forgot a = 10, b = 0, which would be 100.

like image 671
Martin Avatar asked Apr 22 '13 10:04

Martin


1 Answers

Try:

int poss_n[(MAX + 1) * (MAX + 1)] = {0};

This way you allocate enough memory to store your answers.

like image 96
sje397 Avatar answered Sep 20 '22 14:09

sje397