Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

C++ Prime numbers hlp plz?


ghost's Avatar
0 0

Hey all, I need some help creating a program to print all of the odd numbers from 1 - 1000. I know i need to find the factors of each number in the for loop, but not quite sure how to go about doing that. Any help is much appreciated…thank you in advance!


ghost's Avatar
0 0

Print out the odd numbers?..

#include <iostream>

int main(int argc, char **argv)
{
	for(int i=1; i<=1000; ++i)
		if((i%2) != 0) std::cout << i << " ";
	return 0;
}

or if you meant the prime numbers, than I guess you could do something like..

#include <iostream>

int main(int argc, char **argv)
{
                for(int i=1; i<=1000; ++i)
                {
                                int nFactors = 0;
                                for(int ii=1; ii<=i; ++ii)
                                                if((i%ii) == 0) ++nFactors;
                                if(nFactors <= 2) std::cout << i << " ";
                }
                return 0;
}

Uber0n's Avatar
Member
0 0

Hmm I've written exactly that kind of program iin C++… I'll see if I can find the source later on today :D

You can PM me if you want it ^^

Peace B)


ghost's Avatar
0 0

I think my solution is slightly shorter :p, and I can only assume he meant prime instead of odd numbers, small typo 'tis all.

Cheers, ~T


ghost's Avatar
0 0

ahhhh your absolutly right metal, thank you for recognizing my mistake. my keyboard is messed up right now, and it took forever to type out a message, then when i hit enter i got that "unable to connect to sql server" error… so i had to redo it all lol,

thank you very much for the quick responses both of you. i really appreciate it


ghost's Avatar
0 0

dont know if this will help, but it is a divisibility checker that i wrote a while ago. i think that you could take the for loop from it and change to what you need:

#include <iostream>
using namespace std;

void CheckDivis (int num)
{
     int a;
     for(int i=2; i<=10; ++i) {
             a=num%i;
             if (a!=0) cout<<"not divisible by "<<i<<endl;
             else cout<<"divisible by "<<i<<endl;
     }
}

int main ()
{
    int b;
    cout<<"CheckDivis:";
    cin>>b;
    if(b>100000000) {cout<<"Number too large\n"; system("PAUSE"); return 0;}
    CheckDivis(b);
    cout<<endl;
    main ();
}