help

how to make a programm in native c++ which print out all prime numbers less than or equal to given number????????
You could implement this:
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

Or you could take the easy route and just do something like
1
2
3
4
5
for (int i = 2; i < upperBound; ++i)
{
    if (isPrime(i)) // You'd have to implement this yourself, of course...
        std::cout << i << '\n';
}

(and, of course, there are various optimizations to the above, but the basic idea is there)
i dont under stand .wht u wnt to say?
this is code to chek whteher given number is prime or not...now question is that where should be loop held to take decrement and chek again till it reaches 1???









#include<iostream>

using namespace std;

int main()
{
int c=0;
int a;
int k=1;
cin>>a;
while(k<=a)
{
if(a%k==0)
{
c=c+1;
}
k++;
}
if(c==2)
{
cout<<"prime"<<a;

}
else
{
cout<<"not prime"<<a;
}
}
Well then you could just put all of that in a for loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

int main() {
        int a;
        std::cin >> a;

        for (a; a > 1; --a) {

                int c = 0, k = 1;
                while (k <= a) {
                        if (a % k == 0) {
                                c += 1;
                        }
                        k++;
                }
                if (c == 2) {
                        std::cout << "prime " << a;
                } else {
                        std::cout << "not prime " << a;
                }
                std::cout << std::endl;
        }
}
1
2
3
4
5
6
7
for(unsigned int x = 0; x < INFINITY /* INFINITY is defined */; x++)
{
    if((x % 2) == 1)
    {
         cout<< "i found it, I FOUND IT."<< endl;
    }
}


Probably one of the easiest things you could do. I suggest you study the code and figure out the mechanics involved, as you will be using them in everything.


Oops, that finds odd/even numbers. You want to write an algorithm to factor each number.
Last edited on
liyara;
why we declare c and k in for loop??why we cant declare it out of for loop??
Topic archived. No new replies allowed.