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.
Related
I'm writing a code to find the last prime number of a given range. Suppose the range is 1 to 50. Then the last prime no. I want to print must be 47. My idea was to maybe reverse the order of prime numbers in the range and then try printing only the first value. Again kinda like if my order was 1 to 50 then I would start printing from 47, 43 and so on and only print 47. But I'm stuck and not getting ideas on how I could do this. here's my code
int prime_bef(int n)
{
int check = 0;
for (int i = 1; i <= n; i++)
{
if (n % i == 0)
{
check++;
}
}
if (check == 2)
{
cout << n << " ";
}
return 0;
}
int main ()
{
int l;
int u;
cin >> l >> u;
for (int i = u; i >= l; i--)
{
prime_bef(i);
}
return 0;
}
You can just use exit() in the place you want to end the program, and it works fine in your case. But by far the best approach is returning a value to test for continuation, it is the most readable.
#include<iostream>
#include <stdlib.h>
using namespace std;
int prime_bef(int n)
{
int check = 0;
for (int i = 1; i <= n; i++)
{
if (n % i == 0)
{
check++;
}
}
if (check == 2)
{
cout << n << " ";
exit(0);
}
return 0;
}
int main ()
{
int l;
int u;
cin >> l >> u;
for (int i = u; i >= l; i--)
{
prime_bef(i);
}
return 0;
}
Same code using bool return type:
#include<iostream>
using namespace std;
bool prime_bef(int n)
{
int check = 0;
for (int i = 1; i <= n; i++)
{
if (n % i == 0)
{
check++;
}
}
if (check == 2)
{
cout << n << " ";
return true;
}
return false;
}
int main ()
{
int l;
int u;
cin >> l >> u;
for (int i = u; i >= l; i--)
{
if(prime_bef(i))
break;
}
return 0;
}
Here is a simple and efficient way to check if the number is prime. I am checking if the number is prime and when it is true I am printing the number and breaking the loop so that only 1 number is printed. You can always remove the break statement and print all prime numbers in range.
#include<iostream>
using namespace std;
bool isPrime(int n){
if(n==2)return true;
if(n%2==0 || n==1)return false;
for(int i=3; i*i<=n; ++i){
if(n%i==0){
return false;
}
}
return true;
}
int main (){
int l, u;
cin>>l>>u;
for (int i = u; i >= l; i--){
if(isPrime(i)){
cout<<i<<"\n";
break;
}
}
return 0;
}
I'll give you a hint... while you are iteratively checking for the prime nature of the number, also check whether the last prime number calculated in the loop is greater than the max term of the range and break the loop when the condition becomes false.
Here a C++17 approach :
#include <cmath>
#include <iostream>
#include <vector>
// type to use for storing primes
using prime_t = unsigned long;
// there is a way to determine an upper bound to the number of primes smaller then a maximum number.
// See : https://primes.utm.edu/howmany.html
// this can be used to estimate the size of the output buffer (vector)
prime_t pi_n(const prime_t max)
{
prime_t pi_n{ max };
if (max > 10)
{
auto ln_n = std::log(static_cast<double>(max));
auto value = static_cast<double>(max) / (ln_n - 1.0);
pi_n = static_cast<prime_t>(value + 0.5);
}
return pi_n;
}
// Calculate prime numbers smaller then max
// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
auto calculate_primes(const prime_t max)
{
std::vector<bool> is_primes(max, true);
// 0, 1 are not primes
is_primes[0] = false;
is_primes[1] = false;
// sieve
for (prime_t n = prime_t{ 2 }; n < prime_t{ max }; ++n)
{
if (is_primes[n])
{
auto n2 = n * n;
for (prime_t m = n2; m < max; m += n)
{
is_primes[m] = false;
}
}
}
// avoid unnecessary resizes of vector by pre-allocating enough entries to hold result
prime_t n{ 0 };
std::vector<prime_t> primes;
primes.reserve(pi_n(max));
// add all prime numbers found by the sieve
for (const auto is_prime : is_primes)
{
if (is_prime) primes.push_back(n);
n++;
}
return primes;
}
int main()
{
const prime_t max{ 50 };
auto primes = calculate_primes(max);
// max prime is last one in container
auto max_prime = primes.back();
std::cout << "maximum prime number smaller then " << max << ", is " << max_prime << std::endl;
}
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 5;
int nums[] = {0 ,1};
if (n == 0)
{
return 0;
} else if (n == 1)
{
return 1;
} else{
for (int i = 2; i < n + 1; i++)
{
cout << i << endl;
nums[i] = nums[i-2] + nums[i-1];
}
return nums[n]
}
return 0;
}
It is just a simple fibonacci array, but my code only gives stdout one time and it is two. FYI: this code may not be correct to compute the nth term of fibonacci array, but i am strugglling with this for loop.
I think the condition of i < n+1 is not meet, but why this for loop ends
nums[i] has size 2. You can't access nums[i] for i >= 2. An array doesn't grow. You can't change the size of an array. Use a std::vector. You've already included the header. A return statement finishes a function. In case of the main function it causes the program to stop. The return value of the main function by convention describes if the program was successful or errors occurred. You are returning
return nums[n];
That's probably not your intention. I assume you want to print the vector.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 5;
std::vector<int> nums {0 ,1};
if (n == 0)
{
return 0;
} else if (n == 1) {
return 1;
} else {
nums.reserve(n + 1);
for (int i = 2; i < n + 1; i++)
{
cout << i << '\n';
nums.emplace_back(nums[i-2] + nums[i-1]);
}
for (const auto num : nums)
{
cout << num << '\n';
}
}
return 0;
}
it's because you can't access to nums[2] so the correct version of your code is :
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 5;
int nums[5] = {0 ,1};
if (n == 0)
{
return 0;
} else if (n == 1)
{
return 1;
} else{
for (int i = 2; i < n + 1; i++)
{
cout << i << endl;
nums[i] = nums[i-2] + nums[i-1];
}
return nums[n]
}
return 0;
}
you must provide estimated size to array or you will create vector or some dynamic array..
Your approach always give Segmentation fault;
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 5;
vector<int> nums(n+1);
nums[0]=0;
nums[1]=1;
if (n == 0)
{
return 0;
} else if (n == 1)
{
return 1;
} else{
for (int i = 2; i < n + 1; i++)
{
// cout << i << endl;
nums[i] = nums[i-2] + nums[i-1];
}
for(int i=0;i<n;i++)
{
cout<<nums[i]<<endl; }
}
return 0;
}
*/
So this program will print perfect numbers, but one of them, 2096128, is being printed for some reason? Would really appreciate some help figuring out what is happening! Thank you! I can't figure out why one non perfect number is finding it way into the sequence!
#include <iostream>
#include <string>
#include <math.h>
#include <iomanip>
bool isPerfect(int n);
using namespace std;
int main() {
long long perfect = 0;
int first = 0;
first = (pow(2, 2 - 1))*(pow(2, 2) - 1);
cout << first << endl;
for (int i = 3, j = 1; j < 5; i += 2) {
if (isPerfect(i)) {
perfect = (pow(2, i - 1)*(pow(2, i) - 1));
cout << perfect << endl;
j++;
}
}
// pause and exit
getchar();
getchar();
return 0;
}
bool isPerfect(int n)
{
if (n < 2) {
return false;
}
else if (n == 2) {
return true;
}
else if (n % 2 == 0) {
return false;
}
else {
bool prime = true;
for (int i = 3; i < n; i += 2) {
if (n%i == 0) {
prime = false;
break;
}
}
return prime;
}
}
You're pretty much complicating this task.
Here's what I came up with:
#include <iostream>
using namespace std;
bool isPerfect(long long n);
int main()
{
int count = 5;
long long sum = 1;
for (int i = 3; count >= 0; i += 2)
{
sum += i * i * i;
if (isPerfect(sum))
{
cout << sum << endl;
count--;
}
}
system("pause");
return 0;
}
bool isPerfect(long long n)
{
int sum = 0;
for (int i = 1; i < n; i++)
{
if (n % i == 0)
sum += i;
}
return sum == n;
}
It sure isn't perfect, but will do for 5 numbers. Consider that it'll be very slow for more than 5 numbers.
I wrote simple binary calculator,which I'm going to develop.Everything works for a few first calculations,but after that the program chrashes-"Binary.exe has stopped working".I think there might be something wrong with dynamicly allocated array in function "decToBin()",but i can't spot the issue.Here's the code:
#include <iostream>
#include <math.h>
#include <string>
#include <conio.h>
using namespace std;
void binToDec()
{
string bin;
cout<<"Binary code: ";
cin>>bin;
int powr = 0;
int num = 0;
long long sum = 0;
for(int i=bin.size()-1; i>=0; i--)
{
if(bin[i] == '1')
{
num = 2;
}
else if(bin[i] == '0')
{
num = 0 ;
}
sum += pow(num,powr);
cout<<sum<<endl;
powr++;
}
cout<<"Decimal: "<<sum<<endl;
sum = 0;
powr = 0;
num = 0;
}
void decToBin()
{
int dec = 0;
cout<<"Decimal number or digit: ";
cin>>dec;
int i = 0;
int *numBin = new int[i];
while(dec > 0)
{
numBin[i] = dec%2;
dec = dec/2;
i++;
}
cout<<"Binary: ";
for(int j = i-1; j>=0; j--)
{
cout<<numBin[j];
}
cout<<"\n";
i = 0;
delete [] numBin;
}
int main()
{
//USER INPUT
int nav = 0;
while(true)
{
cout<<"\n";
cout << "1.Binary to decimal:"<<endl;
cout << "2.Decimal to binary:"<<endl;
cin>>nav;
switch(nav)
{
case 1:
{
binToDec();
break;
}
case 2:
{
decToBin();
break;
}
}
}
return 0;
}
Your problem:
int *numBin = new int[i]; //i is 0, then you add elements to it
An easy solution, use std::vector:
vector<int> numBin;
...
numBin.push_back(dec%2);
You don't have to worry about dynamic memory at all now.
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;
}