Error with finding the 10001th prime number - c++

I am currently trying to solve one of project euler's problems, to find the 10001st prime number. Though my code is not returning the right number, and even returned a even number when I changed the starting value of 'count'. Below is my code, if anyone could help me out with this it would be appreciated.
#include <math.h>
#include <iostream>
#include <stdbool.h>
using namespace std;
bool isPrime(int num);
int main()
{
int num = 0, count = 0;
while(count < 10001)
{
num++;
while(isPrime(num) != true)
{
num++;
cout << "\n num: " << num;
}
count++;
isPrime(12);
}
cout << "the 10001's prime number is: " << num << "\n " << count;
system("pause");
return 0;
}
bool isPrime(int num)
{
bool checkPrime = false;
if(num%2 != 0)
{
for(int i = 3; i <= sqrt(num); i++)
{
if(num%i != 0)
{
checkPrime = true;
}
else
{
checkPrime = false;
break;
}
}
}
else
{
return false;
}
if(checkPrime)
{
return true;
}
else
{
return false;
}
}

Your logic in isPrime is wrong. isPrime(3) returns false for instance. The basic problem is that you initialize checkPrime to false instead of true, so that any small number which doesn't enter your for loop returns false even if it's a prime.
Here's a (hopefully) correct version, also with some of the changes Dukeling suggested.
bool isPrime(int num)
{
if (num < 2) // numbers less than 2 are a special case
return false;
bool checkPrime = true; // change here
int limit = sqrt(num);
for (int i = 2; i <= limit; i++)
{
if (num%i == 0)
{
checkPrime = false;
break;
}
}
return checkPrime;
}

Related

Write a program that receives a number from the input and finds the first two prime numbers after it in c++

The task was: Write a program that receives a number from the input and finds the first two prime numbers after it in c++.
I tried
#include <iostream>
// Check, if a number is prime and return true, if it is
bool isPrime(int value) {
bool isPrime = true;
// Try all potential values
for (int i = 2; i <= value / 2; ++i) {
if (value % i == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
int main() {
// Read start value, check, if in OK range
if (int number{}; (std::cin >> number) and (number > 3))
{
int primeCounter = 0;
// Check for the next 2 prime values
while (primeCounter < 2) {
if (isPrime(number)) {
// Prime found
std::cout << number << '\n';
++primeCounter;
}
// Try next number
++number;
}
}
else
{
std::cout << "The input value is not ok\n";
}
}
But the answer was judged as wrong. What could be the reason?
Thank you for your kindness and help!
There are only some minor issues with the code:
The prime check function was not optimized. It worked, but now it is a little bit faster. But does not matter taht much.
The input range check was wrong and, because you wanted to have the primes after the input value. So one increment is necessary.
The corrected code looks like this:
#include <iostream>
// Check, if a number is prime and return true, if it is
bool isPrime(int value) {
// Special cases
if (value < 2) return false;
if (value == 2) return true;
if (value % 2 == 0) return false;
// Brute force
bool isPrime = true;
// Try all potential values
for (int i = 3; i*i < value / 2; i+=2) {
if (value % i == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
int main() {
// Read start value, check, if in OK range
if (int number{}; (std::cin >> number) and (number > 0))
{
// need the next folowing 2 prime numbers
++number;
int primeCounter = 0;
// Check for the next 2 prime values
while (primeCounter < 2) {
if (isPrime(number)) {
// Prime found
std::cout << number << '\n';
++primeCounter;
}
// Try next number
++number;
}
}
else
{
std::cout << "The input value is not ok\n";
}
}

Write a program that will display all prime numbers from the given range

Write a program that will display all prime numbers from the given range. The program must satisfy the following requirements:
a. ask the user of range to display
b. contains the following function:
i. checkRange() – a functions that checks if the entered range is correct or not. A message will be displayed if the range is invalid.
ii. displayPrime() – a function that displays all prime numbers in the given range
NOTE: you will provide the parameter(s) for each function.
here's the code that i made: there is something wrong in my code. I can't pinpoint what is it
#include <iostream>
using namespace std;
int main()
{
int Prime, strt, end, result;
bool isprime=true;
Again:
cout<<"Start: ";
cin>>strt;
cout<<"End: ";
cin>>strt;
cout<<"\n";
if (strt>end)
{
cout<<"Range is Invalid, Try Again."<<"\n";
goto Again;
}
result = Prime(strt,end);
cout<<"Prime numbers in the given range are: "<<result<<endl;
return 0;
}
int Prime(int strt, int end, int num, isprime)
{
int result;
while (strt<end)
{
isprime=true;
if (strt == 0 || strt == 1)
{
isprime = false;
}
for (num = 2; num <= strt/2; ++num)
{
if (strt % num == 0)
{
isprime = false;
break;
}
}
if (isprime)
cout << strt << ", ";
++strt;
}
return result;
}
Here is the answer, there are many issues with the code that I won't go through them, ask if you don't understand something
#include <iostream>
using namespace std;
int prime(int strt, int end)
{
bool isprime;
int count;
while (strt<end)
{
isprime=true;
if (strt == 0 || strt == 1)
{
isprime = false;
}
for (int num = 2; num <= strt/2; ++num)
{
if (strt % num == 0)
{
isprime = false;
break;
}
}
if (isprime) {
cout << strt << ", ";
++count;
}
++strt;
}
return 0;
}
int main()
{
int strt, end, result;
Again:
cout<<"Start: ";
cin>>strt;
cout<<"End: ";
cin>>end;
cout<<"\n";
if (strt>end)
{
cout<<"Range is Invalid, Try Again."<<"\n";
goto Again;
}
cout<<"Prime numbers in the given range are: ";
prime(strt,end);
return 0;
}
This is Probably the simplest way I can put it for you.
#include<iostream>
using namespace std;
int check_range(int a,int b)
{
if (a > b)
return 0;
else
return 1;
}
int check_prime(int a,int b)
{
bool isprime;
while (a < b)
{
isprime=true;
if (a == 0 || a == 1)
{
isprime = false;
}
for (int i = 2; i <= a/2; i++)
{
if (a % i == 0)
{
isprime = false;
break;
}
}
if (isprime) {
cout <<a<<" ";
}
a++;
}
}
int main()
{
int strt,end;
Repeat :
cout<<"Enter the lower limit of range :";
cin>>strt;
cout<<"Enter the upper limit of range :";
cin>>end;
int p = check_range(strt,end);
if (p)
{
check_prime(strt,end);
}
else
{
cout<<"The range is inappropriate.\n";
goto Repeat;
}
}
Hope you would understand.

C++ code not finding 10001th prime

I wrote this code for project euler problem #7(Find the 10001st prime number) but it isn't working and is throwing out all sorts of obviously wrong answers(such as even numbers)
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
long long numprime = 1;
long long counter = 3;
long long arrofprimes[10001];
for(int i = 0; i < 10001; i++)
{
arrofprimes[i] = 2;
}
while(true)
{
if(numprime == 10001)
{
break;
}
bool isprime = true;
for(int i = 0; i < numprime; i++)
{
if((counter % arrofprimes[i]) == 0)
{
isprime = false;
break;
}
}
if(isprime)
{
numprime++;
arrofprimes[numprime - 1] = counter;
}
counter++;
}
cout << counter << endl;
}
You have incremented the counter after finding the 10001st prime, giving you an off-by-one error.

sieve of Eratosthenes C++ algorithm

I am trying to implement this algorithm and I have having a hard time working out the algorithm to work for finding the prime numbers up to 1000. I don't really understand but my code is not giving me the correct output, if you can suggest a way I should change my code I would greatly appreciate it.
#include <iostream>
using namespace std;
bool isPrime(int n);
int main() {
int i;
for(i = 1; i <= 1000; i++){
if( isPrime(i)) cout << "This number " << i << " is a prime. " << endl;
}
}
bool isPrime(int n){
if(n <= 1){
return false;
}
if(n == 2){
return true;
}
for(int i = 2; i < n; i++){
if(n % i == 0){
return false;
}else{
return true;
}
}
}
Your decision inside the for loop inside isPrime() is wrong. This is a criterion to terminate the loop:
if(n % i == 0){
but the elsepart is no reason to terminate. You have to wait until the for loop finished. Like this:
for(int i = 2; i < n; i++){
if(n % i == 0){
// Here, we are sure that n can be divided by any other numbers than 1 and n.
return false;
}
}
// Here, we are sure that n cannot be divided by any number 2 .. (n-1).
return true;
}
By the way, you only have to check until the square root of n. You can spare the rest.
There is problem in your isPrime function
bool isPrime(int n){
if(n <= 1){
return false;
}
if(n == 2){
return true;
}
for(int i = 2; i < n; i++){
if(n % i == 0){
return false;
}
else{
return true; /* this line is very dangerous. When there is odd number it is not divisible by two so the control goes to else block and you get every odd number as your prime number */
}
}
}
Instead use this
bool isPrime(int n){
if(n <= 1){
return false;
}
if(n == 2){
return true;
}
for(int i = 2; i < n; i++){
if(n % i == 0){
return false;
}
}
return true;
}
For Sieve Of Erastosthenes
try this code it may help
int b;
cout << "Enter upper limit" << endl;
cin >> b;
bool *x;
x = new bool[b];
x[2] = true;
for (int i = 2; i < b; i++)
{
int count = 2;
if (x[i])
{
cout << i << endl;
while (i*count < b)
{
x[i*count] = false;
count++;
}
}
}
The problem is in the isPrime function.
Your isPrime function says if the the first value of i (i.e 2) is not divided by n then return true. So for eg. 21, 27 etc are also counted as a prime number.
You can use a flag variable in the isPrime function and used it to determine whether the n is prime or not. Like this
boolean prime = true;
for(int counter = 2; counter <= number / 2; counter++) {
if(number % counter == 0) {
prime = false;
break;
}
}
return prime;
I don't think this is Sieve of Eratosthenes algorithm. If you want to implement this algorithm then you can read from here.

deciding if a number is perfect or prime

the problem is :
"Write a function to find out if a number is a prime or perfect number."
so far i have worked on the perfect part first and this is what i have:
#include <iostream>
using namespace std;
bool perfectNumber(int);
int main()
{
int number;
cout<<"Please enter number:\n";
cin>>number;
bool perfectNumber(number);
return 0;
}
bool perfectNumber(int number)
{
int i;
int sum=0;
for(i=1;i<=number/2;i++)
{
if(number%i==0)
{
sum+=i;
}
}
if (sum==number)
return i;
else
return 0;
}
HOWEVER, there seems to be errors on this code.
I have looked over the book but nothing talks about this topic.
i would like to get advice on how to fix this code.
thanks!
bool perfectNumber(number);
This does not call the perfectNumber function; it declares a local variable named perfectNumber of type bool and initializes it with the value of number converted to type bool.
In order to call the perfectNumber function, you need to use something along the lines of:
bool result = perfectNumber(number);
or:
bool result(perfectNumber(number));
On another note: if you are going to read input from a stream (e.g. cin>>number), you must check to be sure that the extraction of the value from the stream succeeded. As it is now, if you typed in asdf, the extraction would fail and number would be left uninitialized. The best way to check whether an extraction succeeds is simply to test the state of the stream:
if (cin >> number) {
bool result = perfectNumber(number);
}
else {
// input operation failed; handle the error as appropriate
}
You can learn more about how the stream error states are set and reset in Semantics of flags on basic_ios. You should also consult a good, introductory-level C++ book for more stream-use best practices.
void primenum(long double x) {
bool prime = true;
int number2;
number2 = (int) floor(sqrt(x));// Calculates the square-root of 'x'
for (int i = 1; i <= x; i++) {
for (int j = 2; j <= number2; j++) {
if (i != j && i % j == 0) {
prime = false;
break;
}
}
if (prime) {
cout << " " << i << " ";
c += 1;
}
prime = true;
}
}
bool isPerfect( int number){
int i;
int sum=0;
for(i=1;i<number ;i++){
if(number %i == 0){
cout<<" " << i ;
sum+=i;
}
}
if (sum == number){
cout<<"\n \t\t THIS NUMBER >>> "<< number <<" IS PERFECT \n\n";
return i;
}else if (sum |= number) {
cout<<"\nThis number >>> " << number <<" IS NOT PERFECT \n\n";
return 0;
}
}
#pragma hdrstop
#include <tchar.h>
#include <stdio.h>
#include <conio.h>
//---------------------------------------------------------------------------
bool is_prim(int nr)
{
for (int i = 2; i < nr-1; i++) {
if (nr%i==0) return false;
}
return true;
}
bool is_ptr(int nr)
{
int sum=0;
for (int i = 1; i < nr; i++) {
if (nr%i==0) {
sum=sum+i;
}
}
if (sum==nr) { return true;
}
else return false;
}
#pragma argsused
int _tmain(int argc, _TCHAR* argv[])
{
int numar;
printf ("Number=");scanf("%d",&numar);
if (is_prim(numar)==true) { printf("The number is prime");
}
else printf("The number is not prime");
if (is_ptr(numar)==true) { printf(" The number is perfect");
}
else printf(" The number is not perfect");
getch();
return 0;
}