Divisors problem

So I am a bit confused about how to find the prime divisors of a given number.
I figured I could start with 2 and go all the way up to sqrt(number).But now here is the problem, for big numbers is seems to work(or it doesn't, i can't be sure),but I am certain that is doesn't work for small numbers.
Ex:The divisors of 42 are:1 2 3 6 7 14 21 42 , but sqrt(42)=6.4 so it doesn't get to 7.
The code would look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <fstream>
#include <math.h>
using namespace std;
int main()
{
    ifstream f ("data.in");
    ofstream g ("data.out");
    int n,i,j;
    bool prime=true;
    f>>n;
    for(i=2;i<=sqrt(n);i++)
    {prime=true;
     if(n%i==0)
     {
        for(j=2;j<=sqrt(i);j++)
        {
            if(i%j==0) {prime=false; break;}
        }
        if(prime==true) g<<i<<" ";
     }
    }
}

Where should I stop?Or is there a better way to find them?Can someone please tell me the fastest way to do it?
closed account (zwA4jE8b)
you could use ceiling(sqrt(number)) that way it rounds up

or add .5 to it
Last edited on
Your method is wrong. You need to go to sqrt(n) when you're looking for all divisors. Then if n % i == 0 you find two divisors: i and n/i. So if i can go up to 6 it will find 42/6 = 7.

Consider number 26 = 2*13. 13 is prime, but it is nowhere near sqrt(26) ~ 5.

What you need to do, is go from 2 to n and every time you find n % i == 0 ,do n = n/i.
Note that a single prime divisor may go several times.
Ok, I get it,thx for the help.
Ok, I get it,thx for the help.
Topic archived. No new replies allowed.