first off, this is my very first post, so sorry if i sound a little noobish. also, i've only been learning C++ since september, and we're going pretty slow.

so yesterday I got an assignment, using only for loops, and if statements, enter a number, find it's factors, and tell if it's prime or not prime.

my first thought was to figure out if it was prime or not, before getting to the factors, because it sounded simpler. i later found out that the way my teacher wants us to do it, is get the factors, and with those, you'll know if it's prime or not, as there will only be 2 factors (1 and X) if it is prime.

now, i spent maybe 2 hours trying out different things, and i don't have my files from school with me, so i cant post any code that i tried, but some help, at least a point in the right direction would be really appreciated.

I imagine you'll be using the mod operator ( % ) in your "if" statement. As in, given an integer m and a smaller integer n, if m % n is 0, then n is a factor of m.

In C++, that would be something like this:

if (m % n == 0)
{
// code to flag n as a factor of m
}

The if-statement above would likely be inside your for-loop You'll use the above test for various values of n. If the above if-statement is only true when n = 1 or n = m, then m is prime.

It sounds like your teacher wants you to use a brute-force method. Just loop an integer from 1 to n and check to see if it divides evenly into your number. If it does, then it is a factor.

Your choice of n can be interesting.

In C++, that would be something like this:

if (m % n == 0)
{
// code to flag n as a factor of m
}

Another option if you don't know the % operator is

if ( ((m/n) * n) == m)
{
    // n is a factor of m
}

This uses the knowledge that integer division does not deal with decimals. 15/4 = 3

Another option if you don't know the % operator is

if ( ((m/n) * n) == m)
{
    // n is a factor of m
}

This uses the knowledge that integer division does not deal with decimals. 15/4 = 3

I do know what a modulus is.. . .and thank you everyone, i'll try it today when i go to class.

mod (%) takes the division of 2 numbers and returns the remainder. For example:
5%3 = 2
10%5 = 0

...and so on.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.