What's the simplest way to write a Prime Factorization program in C++?

(A program that lists all prime factors of a number)

Edited by JTX: n/a

8 Years
Discussion Span
Last Post by NathanOliver

This is not my homework you retard.


PF(int n)
loop x=2 to sqrt(n)
    if (n==1) 
    if (n%x==0)
         print x
         print PF(n/x)
         print n

This is what someone suggested but I don't know how it works.


Please refrain from name calling. Salem is a great poster and has some very good advice. you did not post any code or say what this is for so even i though it was asking for homework help. it is best to clearly state what is going on becuase we have no information to go on besides what you have posted.

with that siad i would suggest 2 loops. since you could have multiple's of the same number as a factor. the first loop would run through each digit and the second loop would divide the number as many times as it can by that number. a for loop and a while loop would probably work great.

a good example is the number 8. its factors are 2-2-2 but with your code as above you would get 2-4 which is not correct. my approach would test 2 multiply times and give as an output 2-2-2.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.