My program takes a user input, int n, and prints out the first n amount of prime numbers. This is working as intended
eg. if user inputs 8 as n. the program will print :
2 3 5 7 11 13 17 19
My problem is adding the function isPrime(n) (which is not allowed to be changed)
here is what i've tried but im just getting the output :
2 3 5 7 11 13 17 19 0 is not a prime number,
when it should read 2 3 5 7 11 13 17 19 8 is not a prime number
#include "prime.h"
#include <iostream>
int main()
{
int n;
std::cout << "Enter a natural number: ";
std::cin >> n;
for (int i = 2; n > 0; ++i)
{
bool Prime = true;
for (int j = 2; j < i; ++j)
{
if (i % j == 0)
{
Prime = false;
break;
}
}
if (Prime)
{
--n;
std::cout << i << " ";
}
}
if (isPrime(n))
{
std::cout << n << " is a prime number." << std::endl;
}
else
{
std::cout << n << " is not a prime number." << std::endl;
}
system("pause");
}
prime.h :
#ifndef PRIME_H_RBH300111
#define PRIME_H_RBH300111
bool isPrime(int);
#endif
#pragma once
the definition of isPrime(int)
prime.cpp :
#include <cmath>
#include "prime.h"
bool isPrime(int n)
{
if (n < 2)
{
return false;
}
else if (n == 2)
{
return true;
}
else if ((n % 2) == 0)
{
return false;
}
}
I cannot alter the .h file of prime.cpp
I just need the isPrime(n) function to work on the main() function code
the user input n, does not seem to be taking the number 8. but instead 0
giving me the output. 0 is not a prime number
rather than : n (8) is not a prime number
You are decrementing n in the loop. At the time the loop exits, the value of n is 0.
You can solve the problem by:
Using another variable to use in the loop.
Keeping a copy of the n and resetting the value of n after the loop exits.
Here's the second method:
int copyN = n;
for (int i = 2; n > 0; ++i)
{
...
}
n = copyN;
if (isPrime(n))
...
You are decrementing n in the for loop. The for loop has the condition 'n > 0', so you know n isn't > 0 when the loop finishes. You could either save the value of n in a different variable (i.e. "int nOrig = n;") and use that for the prime test, or use a different variable in the loop.
Related
can someone help me out? I've been trying to get this program to print and add all prime numbers in the Fibonacci Sequence below 1000. Just typing the regular Fibonacci code works fine and will list the numbers 1 - 987.
However, the moment I put in a prime number checker it all of a sudden stops at 5 (printing "1 1 2 3 5" which is technically correct since they all fall under what a prime is (though 1 doesn't count). However I'm looking to see ALL prime numbers from 1 - 987 in the sequence, and no matter what I do I can't seem to get it to work.
My code's down below, don't mind the lack of a main function, I'm making this function as a part of a bigger program, but it can stand on its own. Currently testing it by just calling it in the main function.
#include <iostream>
using namespace std;
void primethousand() {
int fibo = 1;
int nacci = 1;
int fibonacci = 0;
int fibosum = 0; //used to get the sum of all printed numbers later, once this issue is fixed.
int pchk = 0; /*primecheck, used to check if a number is a prime or not. 1 means not prime, 0 means prime*/
cout << "\nPrime Fibonacci #s under 1000: \n\n";
for (int ctr = 1; fibonacci < 987; ctr++) {
if (ctr == 1) {
cout << fibo << " ";
continue;
} else if (ctr == 2) {
cout << nacci << " ";
continue;
}
fibonacci = fibo + nacci;
fibo = nacci;
nacci = fibonacci;
//cout << fibonacci << " ";
for (int chr = 2; chr < fibonacci; chr++) {
if (fibonacci % chr == 0) {
pchk = 1;
}
}
if (pchk == 0) {
cout << fibonacci << " ";
}
}
}
You should break up the big task into smaller tasks by using functions.
Additionally, the fibonacci sequence is growing strongly exponential. So, there are not so many numbers that can be calculated in C++ standard data types. For example, even the biggest 8 byte unsigned long long or uint64_t can hold only the 94th element of the Fibonacci series.
For Fibonaccis below 1000, it will be just 16 elements.
So, we can easily precalculate all vaues during compile time (so, not during runtime). This will be the fastest possible solution. Also the compile time will be very short. And the memory consumption will be very low.
Please see:
#include <iostream>
#include <array>
#include <cstdint>
// For fibonacci number < 1000, 16 of the series elements will be sufficient
constexpr std::size_t ArraySize{ 16 };
// Calculate all 16 needed fibonacci number during compile time
consteval auto CreateFibonacciNumberArray() {
std::array<std::uint64_t, ArraySize> fs{ 1, 1 };
for (std::size_t i{ 2 }; i < ArraySize; ++i)
fs[i] = fs[i - 1] + fs[i - 2];
return fs;
}
// This is an array with the 16 fibonacci numbers. It is an compile time array
constexpr auto FIB = CreateFibonacciNumberArray();
// Compiletime function to calculate, if fibonacci numbers are prime
constexpr bool isPrime(const std::uint64_t number) {
if (number % 2 == 0 or number <= 2) return false;
for (std::uint64_t i = 3; (i * i) <= number; i += 2)
if (number % i == 0) return false;
return true;
}
// Create a compile time array, to indicate, if a fibnacci number is prinme
consteval auto IsPrime(const std::array<std::uint64_t, ArraySize>& FIB) {
std::array<bool, ArraySize> primeFibonacci{};
for (std::size_t i{}; i < ArraySize; ++i)
primeFibonacci[i] = isPrime(FIB[i]);
return primeFibonacci;
}
// Boolean compile time array that shows, if a fibonacci number is prime
constexpr auto FibIsPrime = IsPrime(FIB);
int main()
{
for (std::size_t i{}; i < ArraySize; ++i) {
std::cout << FIB[i];
if (FibIsPrime[i]) std::cout << "\tis prime";
std::cout << '\n';
}
}
It looks like once pchk is set to 1, you never set it back to zero, so further primes are never noticed..
I was solving a programming problem in C++ which requires examining all the 9! permutation of the 3 X 3 matrix
1 2 3
4 5 6
7 8 9
I think, I have written the correct logic, and infact tested it on a 2 X 2 matrix(by tweaking the code for 2 X 2 from 3 X 3, ofcourse.), which results into the correct output being printed. But when I run the program for the actual constraint(ie. the 3 X 3 matirx), the program terminates with a Segmentation fault. Oddly when debuugged with GDB, it prints out
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff74f6bbc in _int_malloc (av=av#entry=0x7ffff7839b20 <main_arena>,
bytes=bytes#entry=12) at malloc.c:3353
3353 malloc.c: No such file or directory.
Here is the C++ code that I wrote:
#include <bits/stdc++.h>
using namespace std;
int min_count;
map<string, bool> mp;
vector<vector<int>>vec(3, vector<int>(3, 0));
// n <= 17
bool isPrime(int n) {
return n == 2 or n == 3 or n == 5 or n == 7 or n == 11 or n == 13 or n == 17;
}
// get a String representation of the matrix vec
string getStringRepresentation(vector<vector<int>> vec) {
string str = "";
for(auto i : vec) {
for(auto j : i)
str += ('0' + j);
}
return str;
}
void printRecursive(vector<vector<int>> &vec, map<string, bool> &mp, int count) {
string str = getStringRepresentation(vec);
if(str == "123456789" and count <= min_count)
min_count = count;
//cout << str << " " << count << endl;
if(mp[str])
return;
mp[str] = true;
for(int i = 0; i < vec.size(); ++i) {
for(int j = 0; j < vec[i].size(); ++j) {
if(j != vec[i].size() - 1 and isPrime(vec[i][j] + vec[i][j+1])) {
swap(vec[i][j], vec[i][j+1]);
printRecursive(vec, mp, count + 1);
swap(vec[i][j], vec[i][j+1]);
}
if(i != vec.size() - 1 and isPrime(vec[i][j] + vec[i+1][j])) {
swap(vec[i][j], vec[i+1][j]);
printRecursive(vec, mp, count + 1);
swap(vec[i][j], vec[i+1][j]);
}
}
}
}
// solve for each test case
void solve() {
for(auto &i : vec) {
for(auto &j : i) {
cin >> j;
}
}
//cout << getStringRepresentation(vec) << endl;
min_count = INT_MAX;
printRecursive(vec, mp, 0); // recursively examine all possible states.
// if min_count is not changed(i.e. reamains equal to INT_MAX then the required state is unreachable, print -1 to indicate)
cout << (min_count == INT_MAX ? -1 : min_count) << endl;
}
int main() {
int test; // test are the number of test cases, each will invoke the solve() function.
cin >> test;
while(test--)
solve();
}
For a input
1
7 3 2
4 1 5
6 8 9
The program should have been outputting 6 but results in SIGSEGV as mentioned. What am I doing wrong?
Try using debugging print lines to see where the segmentation fault happens. Also, try to store the matrix as an array of 9 elements rather than a matrix.
For some reason, my last prime(int prime) isn't showing up at the end. Any clue ?
fyi: primeEval stands for a flag, if the loop ends && primeEval==2, the number is actually a prime number. qty stands for quantity of primes counted.
int main(){
long primeEval=0,prime=0,qtyprime=0;
time_t timerr=(time(NULL)+10);
for (int i = 2; time(NULL)!=timerr; i++) {
for (int j = 1; j <= i; j++) {
if((i%j)==0 && primeEval<2){
primeEval++;
if (i==j && primeEval==2) {
qtyprime++;
prime=i;
primeEval=0; // Resets for the next number 'i'
}
}
}
}
cout << "last prime found: " << prime << endl << "Ttal primes found: " << qtyprime;
}
New Answer:
With the change in your code you will now loop through all number. The problem with it now is that once you find a non prime number you will never reset primeEval and because of that you will never capture another prime number If you change your code to the following it will work
int main()
{
long primeEval = 0, prime = 0, qtyprime = 0;
time_t timerr = (time(NULL) + 10);
for (int i = 2; time(NULL) != timerr; i++) {
for (int j = 1; j <= i; j++) {
if ((i%j) == 0){
primeEval++; // incmrent factor
}
// if we are at the end and have 2 factors then we are prime
if (i == j && primeEval == 2) {
qtyprime++;
prime = i;
primeEval = 0; // Resets for the next number 'i'
}
// if we reach the end with more than 2 factors reset and go to the next number
if (i == j && primeEval > 2) {
primeEval = 0; // Resets for the next number 'i'
}
}
}
cout << "last prime found: " << prime << endl << "Ttal primes found: " << qtyprime;
cin.get();
return 0;
}
I would also suggest you look at Which is the fastest algorithm to find prime numbers? to find some more efficient ways to get prime numbers.
Old Answer:
In your code you have:
for (int i = 2; time(NULL)!=timerr; i=+2)
So when you start checking from primes you start with 2 which is prime. Then you increment i by 2 so the next number you check is 4 which is an even number. All even numbers are not prime except for 2. Since you are always adding 2 you will always have an even number so the only prime number you will find is 2.
You have different issues:
for (int i = 2; time(NULL)!=timerr; i=+2) {
Here the syntax is just wrong: it must be i+=2, not i=+2, otherwise you will keep setting i to +2 and testing whether 2 is prime.
Then, as others have pointed out, why are you increasing i by 2? If you want to optimize the search, you should increase j by 2, not i! And j should in any case start from 2 (or, given your approach, from 1), and then you should try j = 3 and then you can increase j by 2 without the risk of skipping some important divisors.
Then, you reset primeEval to 0 only if you find a prime. If you test a number i that is not prime, primeEval stays at 2 and you'll never get into the block again.
So the final code could be:
#include <iostream>
using namespace std;
int main(){
long primeEval=0,prime=0,qtyprime=0;
time_t timerr=(time(NULL)+10);
for (int i = 2; time(NULL)!=timerr; i++) {
primeEval=0;
for (int j = 1; j <= i; j++) {
if((i%j)==0 && primeEval<2){
primeEval++;
if (i==j && primeEval==2) {
qtyprime++;
prime=i;
primeEval=0; // Resets for the next number 'i'
}
}
}
}
cout << "last prime found: " << prime << endl << "Ttal primes found: " << qtyprime;
}
Here is my assignment:
A prime number is a number greater than 1 which is only evenly divisible by 1 and itself. For this assignment you will find which numbers from 2 to n (where n is a user-specified number) are prime.
Ask the user for a number, n, greater than 2. Keep asking for a number until a number greater than 2 is provided. Assume that the user will only enter numbers (that is, you do not need to check if a user enters text).
Use a loop to iterate on a variable, i, from 2 through n. For each iteration, check all numbers from 2 through i to determine whether the number is prime. If it is prime, print out i and the word "Prime".
Use the modulus operator, %, to determine if a number is prime
Here is what I have so far. It doesnt work. And I dont know why. please help, im a business student taking basic programming as an elective.
#include <iostream>
using namespace std;
int main()
{
int n;
int i;
int x;
while (n<=2)
{
cout << "Enter a number greater then 2: \n";
cin >> n;
for (x=n; x>=2; x--)
{
bool prime = false;
for (i=2; i<x; i++)
{
if (x%i==0)
{
prime = true;
}
}
if (prime==false)
{
cout << x << " Prime.\n";
}
}
}
return 0;
}
I didn't actually used your code because of indentication it was little bit of hard to read. But I wrote a new method for you. I suggest always divide your code into methods to make it more managable. You can call this in your main method
bool checkPrime(int number)
{ // input: num an integer > 1
// Returns: true if num is prime
// false otherwise.
int i;
for (i=2; i<number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
And here is how can you call this method in the main:
int main()
{
int number;
cout << "Enter an integer (>1): ";
cin >> number;
if (checkPrime(number))
{
cout << number << " is prime." << endl;
}
else
{
cout << number << " is not prime." << endl;
}
// I think this is more convention than anything.
return 0;
}
It may not be the optimal program out there, but this should work:
#include <iostream>
using namespace std;
int main()
{
int n;
int i;
int x;
cout << "Enter a number greater then 2: \n";
cin >> n;
while (n<=2)
{
cout << "Enter a number greater then 2: \n";
cin >> n;
}
for (x=n; x>=2; --x)
{
for (i=2; i<x; ++i)
{
bool prime = true;
for (j=2; j<i/2; ++j)
{
if (i%j==0)
{
prime = false;
break;
}
}
if (prime)
{
cout << j << " Prime.\n";
}
}
}
return 0;
}
There are two easy means to go faster: first there is no need to test potential divisors that are too big (as pointed out by arne), and second, there is no need to test even numbers except 2.
Something like this:
#include <cassert>
bool is_prime(unsigned n)
{
if (n == 2)
return true;
if (n <= 1
|| n % 2 == 0)
return false;
for (int d = 3; d * d < n; ++d)
if (n % d == 0)
return false;
return true;
}
int main()
{
assert(!is_prime(0));
assert(!is_prime(1));
assert(is_prime(2));
assert(is_prime(3));
assert(!is_prime(4));
assert(is_prime(5));
assert(!is_prime(6));
assert(!is_prime(256));
assert(is_prime(257));
}
Of course, even faster is building a table of primes, and using this table as potential divisors, instead of every odd number. Makes sense if you have several numbers to check.
Please, say, why it let say you it does not work? Among others I get this output.
Enter a number greater then 2:
100
97 Prime.
89 Prime.
83 Prime.
79 Prime.
73 Prime.
71 Prime.
67 Prime.
61 Prime.
59 Prime.
53 Prime.
47 Prime.
43 Prime.
41 Prime.
37 Prime.
31 Prime.
29 Prime.
23 Prime.
19 Prime.
17 Prime.
13 Prime.
11 Prime.
7 Prime.
5 Prime.
3 Prime.
2 Prime.
But as int n; leaves n uninitialized, the while loop might not be entered.
I think the Answer 1 function checkprime(int number) can improved but purely on preformance basis, consider the fact that prime numbers cannot be even.So if add an extra check to see if (number % 2 == 0) will reduce a lot of iteration of the for loop, and for the remaining i think iterating the loop from 2 to 9 is enough rather than 2 to n. Too many iterations will slow you down on larger numbers.
I am not sure whether I should ask here or programmers but I have been trying to work out why this program wont work and although I have found some bugs, it still returns "x is not a prime number", even when it is.
#include <iostream>
using namespace std;
bool primetest(int a) {
int i;
//Halve the user input to find where to stop dividing to (it will remove decimal point as it is an integer)
int b = a / 2;
//Loop through, for each division to test if it has a factor (it starts at 2, as 1 will always divide)
for (i = 2; i < b; i++) {
//If the user input has no remainder then it cannot be a prime and the loop can stop (break)
if (a % i == 0) {
return(0);
break;
}
//Other wise if the user input does have a remainder and is the last of the loop, return true (it is a prime)
else if ((a % i != 0) && (i == a -1)) {
return (1);
break;
}
}
}
int main(void) {
int user;
cout << "Enter a number to test if it is a prime or not: ";
cin >> user;
if (primetest(user)) {
cout << user << " is a prime number.";
}
else {
cout << user<< " is not a prime number.";
}
cout << "\n\nPress enter to exit...";
getchar();
getchar();
return 0;
}
Sorry if this is too localised (in which case could you suggest where I should ask such specific questions?)
I should add that I am VERY new to C++ (and programming in general)
This was simply intended to be a test of functions and controls.
i can never be equal to a - 1 - you're only going up to b - 1. b being a/2, that's never going to cause a match.
That means your loop ending condition that would return 1 is never true.
In the case of a prime number, you run off the end of the loop. That causes undefined behaviour, since you don't have a return statement there. Clang gave a warning, without any special flags:
example.cpp:22:1: warning: control may reach end of non-void function
[-Wreturn-type]
}
^
1 warning generated.
If your compiler didn't warn you, you need to turn on some more warning flags. For example, adding -Wall gives a warning when using GCC:
example.cpp: In function ‘bool primetest(int)’:
example.cpp:22: warning: control reaches end of non-void function
Overall, your prime-checking loop is much more complicated than it needs to be. Assuming you only care about values of a greater than or equal to 2:
bool primetest(int a)
{
int b = sqrt(a); // only need to test up to the square root of the input
for (int i = 2; i <= b; i++)
{
if (a % i == 0)
return false;
}
// if the loop completed, a is prime
return true;
}
If you want to handle all int values, you can just add an if (a < 2) return false; at the beginning.
Your logic is incorrect. You are using this expression (i == a -1)) which can never be true as Carl said.
For example:-
If a = 11
b = a/2 = 5 (Fractional part truncated)
So you are running loop till i<5. So i can never be equal to a-1 as max value of i in this case will be 4 and value of a-1 will be 10
You can do this by just checking till square root. But below is some modification to your code to make it work.
#include <iostream>
using namespace std;
bool primetest(int a) {
int i;
//Halve the user input to find where to stop dividing to (it will remove decimal point as it is an integer)
int b = a / 2;
//Loop through, for each division to test if it has a factor (it starts at 2, as 1 will always divide)
for (i = 2; i <= b; i++) {
//If the user input has no remainder then it cannot be a prime and the loop can stop (break)
if (a % i == 0) {
return(0);
}
}
//this return invokes only when it doesn't has factor
return 1;
}
int main(void) {
int user;
cout << "Enter a number to test if it is a prime or not: ";
cin >> user;
if (primetest(user)) {
cout << user << " is a prime number.";
}
else {
cout << user<< " is not a prime number.";
}
return 0;
}
check this out:
//Prime Numbers generation in C++
//Using for loops and conditional structures
#include <iostream>
using namespace std;
int main()
{
int a = 2; //start from 2
long long int b = 1000; //ends at 1000
for (int i = a; i <= b; i++)
{
for (int j = 2; j <= i; j++)
{
if (!(i%j)&&(i!=j)) //Condition for not prime
{
break;
}
if (j==i) //condition for Prime Numbers
{
cout << i << endl;
}
}
}
}
main()
{
int i,j,x,box;
for (i=10;i<=99;i++)
{
box=0;
x=i/2;
for (j=2;j<=x;j++)
if (i%j==0) box++;
if (box==0) cout<<i<<" is a prime number";
else cout<<i<<" is a composite number";
cout<<"\n";
getch();
}
}
Here is the complete solution for the Finding Prime numbers till any user entered number.
#include <iostream.h>
#include <conio.h>
using namespace std;
main()
{
int num, i, countFactors;
int a;
cout << "Enter number " << endl;
cin >> a;
for (num = 1; num <= a; num++)
{
countFactors = 0;
for (i = 2; i <= num; i++)
{
//if a factor exists from 2 up to the number, count Factors
if (num % i == 0)
{
countFactors++;
}
}
//a prime number has only itself as a factor
if (countFactors == 1)
{
cout << num << ", ";
}
}
getch();
}
One way is to use a Sieving algorithm, such as the sieve of Eratosthenes. This is a very fast method that works exceptionally well.
bool isPrime(int number){
if(number == 2 || number == 3 | number == 5 || number == 7) return true;
return ((number % 2) && (number % 3) && (number % 5) && (number % 7));
}