Chat LIVE With Programming Experts! There Are 23 Online Right Now...

 

Code Snippets

  

C++ Source Code


Welcome to Dream.In.Code
Become a C++ Expert!

Join 244,263 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,241 people online right now. Registration is fast and FREE... Join Now!





Finding Factors of a Number Recursively

This recursive function can find factors of a number.

Submitted By: born2c0de
Actions:
Rating:
Views: 5,966

Language: C++

Last Modified: July 29, 2006

Snippet


  1. /*
  2. Written originally by Sanchit Karve AKA born2c0de
  3. */
  4.  
  5.  
  6. #include <iostream>
  7. #include <conio>
  8.  
  9. void factors(long n,long f=1)
  10. {
  11.      if(n%f==0)
  12.           cout<<f<<"  ";
  13.  
  14.      if(f==n)
  15.           return;
  16.  
  17.      factors(n,f+1);
  18. }
  19.  
  20. int main()
  21. {
  22.    factors(37271);
  23.    getch();
  24.    return 0;
  25. }

Copy & Paste


Comments


DrStrangluv 2008-01-31 09:25:18

This code is pretty much equivalent. In fact, it's better since it doesn't put a bunch of function calls on the stack. I wouldn't recommend either. There are much faster (if more complicated) ways to do this. void factors(long n) { for (long f=1;f

DrStrangluv 2008-01-31 09:26:08

Hmm- it cut off most of my comment. Oh well.

born2c0de 2008-02-01 22:43:24

Recursive Solutions for such problems are never the best methods to approach the problem. But learning such techniques is useful if you plan on writing recursive functions of your own for more complicated situations.


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C++ Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month