0
//this is a mine...sieve's algorithm implementation please tell me where i am going wrong...//
#include<iostream>
#include<vector>
using namespace std;
int main()
{
    int a,b,p;
    vector<int> v;
    cin>>a>>b;
    for(int i=a;i<=b;i++)
    v.push_back(i);//inserting all values upto given limit in a vector..
    for(p=2;(p*p)<=b;p++)
    {
                     for(int n=2;(n*p)<=b;n++)
                     {
                             int s=(n*p);
                             v.erase(v.begin()+s);//erase all multiples of 2,3....from vector
                     }
                     }
                     for(int i=0;i<v.size();i++)
                     cout<<v[i]<<endl;
                     }
2
Contributors
1
Reply
15
Views
3 Years
Discussion Span
Last Post by Tumlee
0

You're erasing elements by position rather than by value. Once you start erasing values like that, you can't expect v[number] to be equal to number anymore. A better solution to this problem would be to have an array of bool keep track of which numbers can be prime, and which numbers can't. Instead of removing values from an array, you would just set them to false.

Edited by Tumlee

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.