I wrote this code to print all prime numbers between 3 and 'n' inputted by the user, but upon running, it produces nothing.
Can you please help?
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
for (int candidate = 3; candidate < n; ++candidate)
{
bool isPrime = true;
for (int x = 2; x < n; x++)
{
if (candidate % x == 0)
{
isPrime = false;
}
}
if (isPrime)
{
cout << n << "";
}
}
}
One thing you should know. For checking whether n is prime if we start checking by division operation then you shouldn't check more than sqrt(n).
for (int candidate = 3; candidate < n; ++candidate)
{
bool isPrime = true;
for (int x = 2; x*x < candidate; x++)
{
if (candidate % x == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
cout << candidate << "";
}
}
Better way is to use Sieve of Eratosthenes for this:
isPrime: initialize with all true
for(int i=2;i*i<=n;i++)
for(int j =i*i;j<=n;j+=i)
isPrime[j]=false; // the if was not needed.
Now you know which are primes between 3 and n.
There are several efficiency savings possible in your code. The most efficient method (apart from using a pre-calculated look-up table for small (<1000) n) is the sieve of Erastosthenes.
A very naive version of this algorithm (see also the answer by
coderredoc)
std::vector<int> primes(int n)
{
std::vector<bool> is_prime(n+1,true);
for(auto divisor=2; divisor*divisor <= n; ++divisor)
for(auto candidate=divisor*divisor; candidate <= n; candidate+=divisor)
is_prime[candidate]=false;
std::vector<int> result;
for(auto candidate=2; candidate <= n; ++candidate)
if(is_prime[candidate]) result.push_back(candidate);
return result;
}
essentially reverses the loops over candidates and divisors compared to your original algorithm, but only tests for divisors satisfying divisor*divisor<=candidate.
This algorithm can be substantially improved by realizing that we only need to test for prime divisors (which is the main trick of the sieve)
std::vector<int> primes(int n)
{
std::vector<bool> is_prime(n+1,true);
for(auto divisor=2; divisor*divisor <= n; ++divisor)
if(is_prime[divisor])
for(auto candidate=divisor*divisor; candidate <= n; candidate+=divisor)
is_prime[candidate]=false;
std::vector<int> result;
for(auto candidate=2; candidate <= n; ++candidate)
if(is_prime[candidate]) result.push_back(candidate);
return result;
}
which cuts down on the testing for large n. A further efficiency saving (by a factor ~2 in space and time) is possible by avoiding even candidates and divisors:
std::vector<int> primes(int n)
{
if(n<2) return {};
if(n==2) return {2};
std::vector<bool> is_prime((n+1)>>1,true);
for(auto divisor=3; divisor*divisor <= n; divisor+=2)
if(is_prime[divisor>>1])
for(auto candidate=divisor*divisor; candidate <= n; candidate+=2*divisor)
is_prime[candidate>>1]=false;
std::vector<int> result(1,2);
for(auto candidate=3; candidate <= n; candidate+=2)
if(is_prime[candidate>>1]) result.push_back(candidate);
return result;
}
This algorithm has a poor memory access pattern (into the is_prime[]), which becomes a problem for very large n. A more sophisticated method, segmented sieve, can avoid that, see the above link.
Change your inner loop from
for (int x = 2; x < n; x++)
{
if (candidate % x == 0)
{
isPrime = false;
}
}
to
for (int x = 2; x < candidate; x++)
{
if (candidate % x == 0)
{
isPrime = false;
break;
}
}
otherwise x would eventually become candidate itself and candidate%candidate is 0 which would cause isPrime to become false.
The break statement is used because after being sure that the number is not prime, there's no need of further iterations.
And since you consider only numbers from 3, you could change your outer loop to save some iterations like
for (int candidate = 3; candidate < n; candidate+=2)
This would increment candidate by 2 each time. This is okay because no even numbers greater than 2 are not prime.
Also, if the range of numbers you are considering is inclusive of n, you may modify the outer for loop to
for (int candidate = 3; candidate < n; candidate+=2)
to consider n as well.
It's not recommended to use using namespace std; — because this imports all of the identifiers from std. See this question on Stack Overflow.
Should the end condition of the second loop be candidate instead of n, i.e.
for (int x = 2; x < candidate; x++)//not before N prime numbers divine up to them
{
if (candidate % x == 0)
isPrime = false;
}
Shouldn't you put out candidate instead of n
I think this should work
#include <iostream>
#include <vector>
int main()
{
//setup start parameters
//test sequence
std::vector<int> test_sequence {2};
int end_number, start_number;
start_number = 3;
//take wished end number
std::cin >> end_number;
// test is wished number smaler than start number
if (start_number < end_number)
{
// loop which goes trough every number between start and end number
for (start_number; start_number <= end_number; start_number++)
{
bool isPrime = true;
//test is this number prime
for (int n = 0; n < test_sequence.size(); n++)
{
if (start_number % test_sequence[n] == 0 && start_number != test_sequence[n] )
{
isPrime = false;
}
}
if (isPrime)
{
std::cout << start_number << std::endl;
//hold result for next test
test_sequence.push_back(start_number);
}
}
}
else
{
std::cout << "Wrong input";
}
}
Result for first 200
Related
I am trying, to write a program in C++, that will calculate prime numbers, and store them in an array. Consider this is my third code.
The problem I have run into, is that, while I get Prime numbers, I also get composite numbers, specifically multiples of 5 and 7 (at least until the limit of 30). I know, the code will probably, be terrible, but it was, what I could come up with given my limited experience in both coding and prime numbers.
This is what I've written:
#include <iostream>
int j;
int i = 3;
int prime[30];
int main()
{
for (i; i < 30; i+=2)
{
for (j =i; j>i*i; j--)
{
if ((i % j) == 0)
{
continue;
}
}
prime[i] = i;
std::cout << prime[i] << std::endl;
}
}
output: 3 5 7 9 11 13 15 17 19 21 23 25 27 29
Your inner loop only needs to test divisibility with the prime numbers you've encountered thus far. (e.g. no point in testing divisibility with 9 if you've already tested divisibility with 3)
int main()
{
int j;
int i = 3;
int primes[30];
int primecount = 0;
primes[primecount++] = 2; // hardcode 2, it's the only even number
for (i = 3; i < 30; i += 2)
{
bool isPrime = true;
for (j = 0; j < primecount; j++)
{
if ((i % primes[j]) == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
primes[primecount++] = i;
}
}
for (int k = 0; k < primecount; k++)
{
std::cout << primes[k] << " ";
}
std::cout << std::endl;
}
As CoderCharmander points out in the comments, that continue only breaks from the inner loop but you intended to continue with the outer loop. Smallest fix is to use the dreaded goto, entirely appropriate here.
Also the inner for loop specification is all wrong:
#include <iostream>
int prime[30];
int main()
{
int i, j;
std::cout << 2 << " "; // the first prime is 2
for (i=3; i < 30; i+=2)
{
for // all wrong: (j =i; j>i*i; j--)
(j = 2; j*j <= i; ++j) // or even, (j = 3; j*j <= i; j += 2)
{
if ((i % j) == 0)
{
prime[i] = 0; // initialize the non-primes as well!
goto L1; // continue the outer loop
}
}
// the inner loop finished normally
prime[i] = i;
std::cout << i << " ";
L1: ;
}
}
This also needlessly tests the numbers by all the numbers above 2 smaller than the threshold (or by the odds, as in the commented suggestion) but we only really need to test by primes.
When making this amendment it's important to be careful not to introduce the much bigger inefficiency than the one we were trying to fix (a quadratic loss in time complexity over an intended log factor gain), as there's no point in testing divisibility of e.g. 23 by 5,7,11,13 and 19.
And actually testing divisibility can be avoided altogether, if one so chooses, but that's another matter entirely.
the code is showing wrong results...it is showing 15,21 and many other odd numbers as prime but they are not...how to fix the problem?..what code should I write in main section[inside int main()]?
#include<bits/stdc++.h>
using namespace std;
#define M 1000000
bool marked[M];
bool sieve(int n)
{
for (int i = 3; i * i <= n; i += 2)
{
if (marked[i] == false)
{
for (int j = i * i; j <= n; j += i + i)
{
marked[j] = true;
}
}
}
}
bool isPrime(int n)
{
if (n < 2)
return false;
if (n == 2)
return true;
if (n % 2 == 0)
return false;
return marked[n] == false;
}
int main()
{
int i,j,k,n,m;
cin>>n;
for(i=0; i<n; i++)
{
cin>>m;
if(isPrime(m))
cout<<"prime"<<endl;
else
cout<<"N"<<endl;
}
}
Is the wrong answer coming due to not properly using or calling functions?.....in this case what should be done.....
My guess is that, since you never call the sieve function, your marked array never gets filled. Since marked is not dynamically allocated, it is zeroed out within your program. Hence, in your isPrime function, all odd numbers will cascade through your if statements and then hit the part where marked[n] == false which would return true since marked[n] is 0 for all of its entries, which is equivalent to the boolean false.
You might want to figure out where it would be best to run the sieve function.
You have wrong increment here:
for (int j = i * i; j <= n; j += i + i)
You need to increase j by i, but you actually increase in by 2*i. Anyway I agree with the previous answer that you never call sieve.
I'm trying to save first 20 prime numbers that are greater or equal than entered number.
Right now the output is 20 times 997 because values overwrite previous ones. I can't figure out what to do to limit them. When the array is full stop the loop or something so the overwriting won't happen?
bool is_prime(int num) {
if (num < 2) {
return false;
}
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
void fillArr(int arr[20], int num) {
for (int index = num; index <= 1000; index++) { //don't know how to set up
//2nd condition, depends on entered number
if (is_prime(index)) {
//save first 20 prime numbers that are >= num into an array
//Code fills the array with every prime it finds, setting it for all
//values and overwriting any previous primes it has found. Right now
//output would be the same 20 prime numbers closest to index 1000,
//based on second condition
for (int i = 0; i < 20; i++) {
arr[i] = index;
}
}
}
//print test
for (int i = 0; i < 20; i++) {
std::cout << arr[i] << "\t";
}
}
int main() {
int arr[20];
int num;
std::cout << "Enter number: ";
std::cin >> num;
fillArr(arr, num);
return 0;
}
In your code, initialize i to 0 at the beginning. Each time you encounter a prime, add it to your array and increment i. Break when i >= 20.
void fillArr(int arr[20], int num) {
int i = 0;
for (int index = num; index <= 1000 && i < 20; index++) {
if (is_prime(index)) {
arr[i++] = index;
}
}
//print test
for (int i = 0; i < 20; i++) {
std::cout << arr[i] << "\t";
}
}
Also note that this is not the most optimal way to find primes. For finding whether a given number is prime, you only need to check for whether it is divisible by primes uptil square root of the number (and not till n/2). You may also want to read about the Seive of Eratosthenes.
As also specified in the comments, it's better to use std::vector or std::array rather than raw arrays. In that case, you'd simply want to push_back(index) and break when vector's size >= 20.
Homework: I'm just stumped as hell. I have algorithms set up, but I have no idea how to code this
Just to be clear you do not need arrays or to pass variables by reference.
The purpose of the project is to take a problem apart and using Top-Down_Design or scratch pad method develop the algorithm.
Problem:
Examine the numbers from 2 to 10000. Output the number if it is a Dual_Prime.
I will call a DualPrime a number that is the product of two primes. Ad where the two primes are not equal . So 9 is not a dual prime. 15 is ( 3 * 5 ) .
The output has 10 numbers on each line.
My Algorithm set-up
Step 1: find prime numbers.:
bool Prime_Number(int number)
{
for (int i = 2; i <= sqrt(number); i++)
{
if (number % 1 == 0)
return false;
}
return true;
}
Step 2: store prime numbers in a array
Step 3: Multiply each array to each other
void Multiply_Prime_Numbers(int Array[], int Size)
{
for (int j = 0; j < Size- 1; j++)
{
Dual_Prime[] = Arr[j] * Arr[j + 1]
}
}
Step 4: Bubble sort
void Bubble_Sort(int Array[], int Size) // Sends largest number to the right
{
for (int i = Size - 1; i > 0; i--)
for (int j = 0; j < i; j++)
if (Array[j] > Array[j + 1])
{
int Temp = Array[j + 1];
Array[j + 1] = Array[j];
Array[j] = Temp;
}
}
Step 5: Display New Array by rows of 10
void Print_Array(int Array[], int Size)
{
for (int i = 0; i < Size; i++)
{
cout << Dual_Prime[i] << (((j % 10) == 9) ? '\n' : '\t');
}
cout << endl;
}
I haven't learned dynamic arrays yet,
Although dynamic arrays and the sieve of Eratosthenes are more preferable, I tried to write minimally fixed version of your code.
First, we define following global variables which are used in your original implementation of Multiply_Prime_Numbers.
(Please check this post.)
constexpr int DP_Size_Max = 10000;
int DP_Size = 0;
int Dual_Prime[DP_Size_Max];
Next we fix Prime_Number as follows.
The condition number%1==0 in the original code is not appropriate:
bool Prime_Number(int number)
{
if(number<=1){
return false;
}
for (int i = 2; i*i <= number; i++)
{
if (number % i == 0)
return false;
}
return true;
}
In addition, Multiply_Prime_Numbers should be implemented by double for-loops as follows:
void Multiply_Prime_Numbers(int Array[], int Size)
{
for (int i = 0; i < Size; ++i)
{
for (int j = i+1; j < Size; ++j)
{
Dual_Prime[DP_Size] = Array[i]*Array[j];
if(Dual_Prime[DP_Size] >= DP_Size_Max){
return;
}
++DP_Size;
}
}
}
Then these functions work as follows.
Here's a DEMO of this minimally fixed version.
int main()
{
int prime_numbers[DP_Size_Max];
int size = 0;
for(int j=2; j<DP_Size_Max; ++j)
{
if(Prime_Number(j)){
prime_numbers[size]=j;
++size;
}
}
Multiply_Prime_Numbers(prime_numbers, size);
Bubble_Sort(Dual_Prime, DP_Size);
for(int i=0; i<DP_Size;++i){
std::cout << Dual_Prime[i] << (((i % 10) == 9) ? '\n' : '\t');;
}
std::cout << std::endl;
return 0;
}
The Sieve of Eratosthenes is a known algorithm which speeds up the search of all the primes up to a certain number.
The OP can use it to implement the first steps of their implementation, but they can also adapt it to avoid the sorting step.
Given the list of all primes (up to half the maximum number to examine):
Create an array of bool as big as the range of numbers to be examined.
Multiply each distinct couple of primes, using two nested loops.
If the product is less than 10000 (the maximum) set the corrisponding element of the array to true. Otherwise break out the inner loop.
Once finished, traverse the array and if the value is true, print the corresponding index.
Here there's a proof of concept (implemented without the OP's assignment restrictions).
// Ex10_TwoPrimes.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void Homework_Header(string Title);
void Do_Exercise();
void Sieve_Of_Eratosthenes(int n);
void Generate_Semi_Prime();
bool Semi_Prime(int candidate);
bool prime[5000 + 1];
int main()
{
Do_Exercise();
cin.get();
return 0;
}
void Do_Exercise()
{
int n = 5000;
Sieve_Of_Eratosthenes(n);
cout << endl;
Generate_Semi_Prime();
}
void Sieve_Of_Eratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
memset(prime, true, sizeof(prime));
for (int p = 2; p*p <= n; p++)
{
// If prime[p] is not changed, then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
bool Semi_Prime(int candidate)
{
for (int index = 2; index <= candidate / 2; index++)
{
if (prime[index])
{
if (candidate % index == 0)
{
int q = candidate / index;
if (prime[q] && q != index)
return true;
}
}
}
return false;
}
void Generate_Semi_Prime()
{
for (int i = 2; i <= 10000; i++)
if (Semi_Prime(i)) cout << i << "\t";
}
So the point is to have the program find and list all prime numbers between 1 and the number you enter. I'm using number_test as the number tested for prime, and divisor and the number to divide by.
I'm not sure what's wrong, as to me it looks functionally the same as the program posted here: Printing prime numbers from 1 through 100
with some minor changes (inputting a number, changing "i" to less than the number entered).
I've been looking for the past three or four days, and I haven't found anything that really answers this question fully, to the degree I need for class. Any help is much appreciated.
#include iostream
#include conio.h
using namespace std;
void main(void){
//Declare variables
int number_entered;
//Get inputs
cout << "This program lists all prime numbers from 1 through a positive number entered."
<< endl;
cout << "Please enter a positive integer."
<< endl;
cin >> number_entered;
cout << "Displaying all numbers from 1 to " << number_entered
<< endl
<< "Press any key to continue..."
<< endl;
getch();
for(int number_test = 2; number_test < number_entered; number_test++){
for(int divisor = 2; divisor < number_test; divisor++){
if(number_test % divisor == 0){
break;
}
else if(number_test % divisor != 0){
cout << number_test << " ";
break;
}
}
}
getch();
}
You should use the Sieve of Eratosthenes to compute the primes less than n. Begin by making a list of all numbers from 2 to the maximum desired prime n. Then, at each iterative step, the smallest remaining number that hasn't yet been considered is output and all of its multiples are crossed off the list.
function primes(n)
sieve := makeArray(2..n, True)
for p from 2 to n step 1
if sieve(p)
output p
for i from p*p to n step p
sieve[i] := False
This O(n log log n) algorithm is very fast; you should be able to compute the 78498 primes less than a million in less than a second.
A simple C++ Program to find the "N" prime numbers.
#include <iostream >
using namespace std;
int main()
{
int N;
cin >> N;
for (int i = 2; N > 0; ++i)
{
bool isPrime = true ;
for (int j = 2; j < i; ++j)
{
if (i % j == 0)
{
isPrime = false ;
break ;
}
}
if (isPrime)
{
--N;
cout << i << "\n";
}
}
return 0;
}
Just a small suggestion. Since prime numbers are odd, even numbers can be left out.
For example, in below loops, i and j increase by 2 (i +=2) instead of by 1 (i ++).
for (int i=3;i<=numberByUser; i+=2){
for (j=3;j<=i;j +=2){
if (i%j==0){
break;
}
}
i think in your answer any way one time the loop will terminated(i am talking about the loop checking the whether it is prime or not)once it comes out you don't know whether it made the break or not.So try to make a flag variable and check outside.I ope that will work
for(n=lower+1; n<upper; n++)
{
prime = 1;
for(i=2; i<n; i++)
if(n%i == 0)
{
prime = 0;
break;
}
if(prime)
printf("\n\n\t\t\t%d", n);
}
for(int number_test = 2; number_test < number_entered; number_test++){
for(int divisor = 2; divisor < number_test; divisor++){
if(number_test % divisor == 0){
break;
}
else if(number_test % divisor != 0){
cout << number_test << " ";
break;
}
}
}
The above code will not show you the prime numbers, it will just show you the number you entered if/when you run into a divisor that is not a factor of the number. For example, if you enter "9", you will start at 2, which is not a factor of 9, so you will show "9" (incorrectly) as a "prime", when it is not.
The easiest method for testing if a number is a prime is by checking all prime numbers below it's square root to see if they are factors of the given number. If none of them are (then none of the non-prime numbers below the given number will be either), the number is a prime number. If it has at least one prime factor less than or equal to it's square root, it is not prime.
Since you are looking to show all primes in a range of [0, X], you can simply check your list of factors as you go along (or do it in reverse, which is effectively what the Sieve of Eratosthenes does).
When my point was like your one, I wrote this code, it worked. Hope it will help you.
#include <cstdio>
#include <vector>
using namespace std;
vector <int> sn;
bool isPrime(int n) {
if (n <= 1) {
return 0;
}
if (n == 2) {
return true;
}
if (!(n % 2)) {
return false;
}
for (int i = 2; i*i <= n; i++) {
if (!(n % i)) {
return 0;
}
}
return 1;
}
void primeNumbers(int k) {
sn.push_back (2);
int i = 3, j = 1;
for ( ; j < k + 1; i += 2 && j++) {
if (isPrime(i)) {
sn.push_back(i);
}
}
}
int main() {
int i, k;
scanf("%d", &k);
primeNumbers(k);
for (i = 0; i < sn.size(); i++) {
printf("%d ", sn[i]);
}
return 0;
}
int getNumberOfPrimes(int N) {
bool *numbers = new bool[N-1]();
for (int i = 2; i <= N/2; ++i) {
if (numbers[i-2] == true) continue;
for (int j = i+i; j <= N; j = j+i) {
numbers[j-2] = true;
}
}
int count = 0;
for (int i = 0; i < (N-1); ++i) {
if (numbers[i] == false) ++count;
}
delete []numbers;
return(count);
}
Man I guess I have the simplest methode of this all. Hope it works for you!
#include < iostream >
using namespace std;
int main()
{
int n, i, j
cin>>n; //The max limith
for(i=2; i<=2; i++)
{
for(j=1; j<=i/2; j++)
if(i%j!=o)
cout<<i;
}
return 0;
}
If a number has divisors, at least one of them must be less than or equal to the square root of the number. When you check divisors, you only need to check up to the square root, not all the way up to the number being tested.