Factors of an integer: Difference between revisions
Content added Content deleted
(Undo revision 101016 by 81.255.154.129 (previous version worked fine; no need to make it more complex)) |
|||
Line 272: | Line 272: | ||
=={{header|C}}== |
=={{header|C}}== |
||
<lang c>#include < |
<lang c>#include <stdio.h> |
||
#include < |
#include <stdlib.h> |
||
typedef struct |
typedef struct { |
||
⚫ | |||
{ |
|||
⚫ | |||
⚫ | |||
⚫ | |||
} Factors; |
} Factors; |
||
void xferFactors(Factors *fctrs, int *flist, int flix) |
void xferFactors( Factors *fctrs, int *flist, int flix ) |
||
{ |
{ |
||
int ix, ij; |
|||
int newSize = fctrs->count + flix; |
|||
if (newSize > flix) { |
|||
⚫ | |||
fctrs->list = realloc( fctrs->list, newSize * sizeof(int)); |
|||
⚫ | |||
⚫ | |||
else { |
|||
⚫ | |||
⚫ | |||
} |
|||
for (ij=0,ix=fctrs->count; ix<newSize; ij++,ix++) { |
|||
⚫ | |||
} |
|||
⚫ | |||
} |
} |
||
Factors *factor(int num, Factors *fctrs) |
Factors *factor( int num, Factors *fctrs) |
||
{ |
{ |
||
int flist[301], flix; |
|||
int dvsr; |
|||
flix = 0; |
|||
fctrs->count = 0; |
|||
if (fctrs->list) free(fctrs->list); |
|||
fctrs->list = NULL; |
|||
for (dvsr=1; dvsr*dvsr < num; dvsr++) { |
|||
fctrs->list = NULL; |
|||
if (num % dvsr != 0) continue; |
|||
⚫ | |||
{ |
|||
⚫ | |||
⚫ | |||
flix = 0; |
|||
continue; |
|||
} |
|||
⚫ | |||
{ |
|||
flist[flix++] = num/dvsr; |
|||
⚫ | |||
} |
|||
⚫ | |||
⚫ | |||
flist[flix++] = dvsr; |
flist[flix++] = dvsr; |
||
if (flix > 0) |
|||
⚫ | |||
} |
|||
if (dvsr*dvsr == num) |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
} |
} |
||
int main(int argc, char |
int main(int argc, char*argv[]) |
||
{ |
{ |
||
int nums2factor[] = { 2059, 223092870, 3135, 45 }; |
|||
Factors ftors = { NULL, 0}; |
|||
char sep; |
|||
int i,j; |
|||
for (i=0; i<4; i++) { |
|||
factor( nums2factor[i], &ftors ); |
|||
{ |
|||
printf("\nfactors of %d are:\n ", nums2factor[i]); |
|||
⚫ | |||
(void) printf("\nfactors of %d are:\n ", nums2factor[i]); |
|||
for (j=0; j<ftors.count; j++) { |
|||
⚫ | |||
printf("%c %d", sep, ftors.list[j]); |
|||
sep = ','; |
|||
{ |
|||
} |
|||
(void) printf("%c %d", sep, ftors.list[j]); |
|||
printf("\n"); |
|||
} |
} |
||
return 0; |
|||
(void) printf("\n"); |
|||
} |
|||
return EXIT_SUCCESS; |
|||
}</lang> |
}</lang> |
||