Answers for "sieve of eratosthenes c"

C
6

prime of sieve

//sieve of eratosthenes or prime of sieve
#include<iostream>
#include<math.h>
using namespace std;
void primeofsieve(long long int n)
{
	long long int arr[n]={};
	for(int i=2;i<=sqrt(n);i++)
	{
		for(long long int j=i*i;j<=n;j+=i)
			arr[j]=1;
	}
	for(long long int i=2;i<=n;i++)
	{
	    if(arr[i]==0)
	    	cout<<i<<" ";
	}


}
int main()
{

	#ifdef _DEBUG
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
    #endif
	long long int n;
	cin>>n;
	cout<<"PRIME NUMBERs ARE : ";
	primeofsieve(n);
	return 0;
}
Posted by: Guest on May-27-2020
0

sieve of eratosthenes c

/******************************************************************************

                            Online C Compiler.
                Code, Compile, Run and Debug C program online.
Write your code in this editor and press "Run" button to compile and execute it.

*******************************************************************************/

#include <stdio.h>
#include <math.h>
#include <stdbool.h>

int main()
{
    int n,i,j; //declaring required variables
    scanf("%d",&n); //scanning n(limit numbers)
    bool arr[n+1]; //declaring an array which contains true and false values
    arr[1]=false; //setting the first index to false (1 is not a prime number)
    
    for(i=2;i<=n;i++){
        arr[i]=true; //we are assuming that all the numbers are true which means prime
    }
    
    for(i=2;i<sqrt(n)+1;i++){ //running loop to the sqrt on n + 1
        if(arr[i]==true){ //if the number is true of prime 
            for(j=i+i;j<=n;j+=i){ //run the loop to n
                arr[j]=false; //assume that the divisble numbers are not prime
            }
        }
    }
    
    for(i=2;i<=n;i++){
        if(arr[i]==true){
            printf("%d ",i); //printing the numbers if that is true 
        }
    }
    
    

    return 0;
}
Posted by: Guest on September-27-2021

Code answers related to "C"

Browse Popular Code Answers by Language