+ 5
Factors of a Number
I want to write a function which can return the factors of a given number as an array...I know how to write the factors program but I don't know how to return the factors as an array. ex.(not correct code) function(number) return factors; I know I can use vectors in C++.. but I don't want to overload the '<<' operator in order to output the array
13 Respostas
+ 8
int factors(int number) {
int factor[];
for(int i = 1; i <= number; i++)
if(number % i == 0)
factor.push(i); // imaginary push method
return factor;
}
I want something like this in C or C++
C++ - vectors..but cout can't output the full array
+ 7
@John Wells, an example code would be great!
Thanks!
+ 5
@Swim, I already knew that.. but I want a simpler way like in javascript where you can console.log() the whole array without any problems. I just want this for my code 'Common Functions(C++)' which you can see in my codes
Anyways, Thanks!
+ 4
@~ swim ~
Thank you so much, for the answer in detail, it really helps a lot, learned more things now, curiosity answered, and yes, I am keeping in mind that note for not mixing the two allocation methods for my future references : )
Huge Thanks!
+ 4
@~ swim ~
Much thanks again! I think I will stick with the new...delete way instead, at least for now, I really haven't touched the mysterious land of C much at all, I guess I'll take the safe route until I have better understanding of C language, later : )
(Edit)
@Cool Codin I am sorry about this question in your thread, I was just following the discussion of the three of you, then I saw @John Wells' code, thus the question came to mind. I hope you can understand : )
+ 3
@Cool Codin, @~ swim ~, @John Wells can someone help me understand the difference between free and delete, where and when we should use either one, please?
+ 2
I updated to allocate 20 array elements at a time.
+ 2
If you truly want JavaScript features, make a class to provide them. You can base it off one of the built-in classes of c++ and provide your push/pop, shift/unshift, <<, etcetera.
+ 1
I'd generate the factors. Allocate storage for them plus a count of how many. Store the count first followed by the factors and return the pointer.
+ 1
Since I don't happen to have a factor function handy, I'll toss a few random numbers. Give me a bit to code.
+ 1
It is currently limited to max of 100 factors.
+ 1
Actually, with realloc you could allocate 100 via pointer and increase when it was used up to avoid array/copying.