Project Euler 10 exercise - c++

What is the sum of all the primes below 2000000?
Example of sum below 10 is 2+3+5+7 = 17
I wrote this code, but still getting the wrong answers:
I tested for numbers lower than a few hundreds, and it has shown the correct answers.
#include <iostream>
#include <math.h>
using namespace std;
bool isPrime(long n)
{
if (n < 2)
return false;
if (n == 2)
return true;
if (n == 3)
return true;
int k = 3;
int z = (int)(sqrt(n) + 1); // square root the n, because one of the product must be lower than 6, if squared root of 36
if (n % 2 == 0)
return false;
while (n % k != 0)
{
k += 2;
if (k >= z)
return true;
}
return false;
}
long primeSumBelow(long x)
{
long long total = 0;
for (int i = 0; i < x; i++) // looping for times of prime appearing
{
if (isPrime(i) == true)
total += i;
if (isPrime(i) == false)
total += 0;
}
cout << "fd" << endl;
return total;
}
int main()
{
cout << primeSumBelow(20) << endl;
cout << primeSumBelow(2000000) << endl;
system("pause");
return 0;
}

The total counter's type is correctly long long. Unfortunately the function primeSumBelow returns only long so, depending on the platform, the correctly calculated result is truncated when it's returned from this function.

Related

Floating point exception: 8 on Smith number check

So I have written a code to check if a long int number is Smith, but I keep getting Floating point exception: 8, no matter what size do I fix my variables in. Not quite sure what I am missing.
#include <iostream>
bool isPrime(long int k) {
if (k == 1) return false;
for (long int i = 2; i*i < k; i++)
if (k % i == 0)
return false;
return true;
}
int main(){
long int n;
std::cin >> n;
long int sumPr = 0, sumCif = 0;
while (n > 0) {
sumCif += n % 10;
n = n/10;
}
for (long int i = 0; i*i<=n/2; i++) {
if (isPrime(i)) {
while (n % i == 0){
long int p = i;
while (p > 0) {
sumPr += (p % 10);
p = p/10;
}
n = n/i;
}
}
}
if (sumPr == sumCif) std::cout << "1" ; else std::cout << "0";
return 0;
}
The limits of this loop appear to be flawed:
for (long int i = 0; i*i<=n/2; i++) {
Possibly partly due to copy and paste from isPrime(). But the larger problem is you need to modularize this code so that you can properly test each component. And reuse modules (e.g. you implement sum of digits of a number twice in your code.) Code duplication is a potential source of error.
#include <iostream>
bool isPrime(long number) {
if (number < 2) {
return false;
}
if (number % 2 == 0) {
return (number == 2);
}
for (long divisor = 3; divisor * divisor <= number; divisor += 2) {
if (number % divisor == 0) {
return false;
}
}
return true;
}
long sum_digits(long number) {
long sum = 0;
while (number > 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
long sum_prime_factor_digits(long number) {
long sum = 0;
for (long divisor = 2; divisor <= number; divisor++) {
if (isPrime(divisor)) {
while (number % divisor == 0) {
sum += sum_digits(divisor);
number /= divisor;
}
}
}
return sum;
}
bool is_smith(long number) {
if (isPrime(number)) {
return false; // only composites can play this game
}
return sum_digits(number) == sum_prime_factor_digits(number);
}
int main() {
long number;
std::cin >> number;
if (is_smith(number)) {
std::cout << "1";
} else {
std::cout << "0";
}
std::cout << "\n";
return 0;
}
TESTS
> ./a.out
4
1
> ./a.out
5
0
> ./a.out
6
0
> ./a.out
22
1
> ./a.out
4937775
1
> ./a.out
15966114
1
>
Writing clean code isn't something you do after the fact, it's what you do to help you in the debugging process.

What does "not all control paths return a value" mean and how to troubleshoot. (C++)

I'm trying to create a function for an assignment that finds the two prime numbers that add up to the given sum. The instructions ask
"Write a C++ program to investigate the conjecture by listing all the even numbers from 4 to 100,000 along
with two primes which add to the same number.
Br sure you program the case where you find an even number that cannot be expressed as the sum of two
primes (even though this should not occur!). An appropriate message to display would be “Conjecture
fails!” You can test this code by seeing if all integers between 4 and 100,000 can be expressed as the sum
of two primes. There should be lots of failures."
I have created and tested the "showPrimePair" function before modifying it to integrate it into the main program, but now I run into this specific error
"C4715 'showPrimePair': not all control paths return a value"
I have already done my research to try to fix the error but it still
remains.
#include <iostream>
#include <stdio.h>
//#include <string> // new
//#include <vector> //new
//#include <algorithm>
using namespace std;
bool isPrime(int n);
//bool showPrimePair(int x);
//vector <int> primes; //new
const int MAX = 100000;
//// Sieve Sundaram function // new
//
//void sieveSundaram()
//{
// bool marked[MAX / 2 + 100] = { 0 };
// for (int i = 1; i <= (sqrt(MAX) - 1) / 2; i++)
// for (int j = (i * (i + 1)) << 1; j <= MAX / 2; j = j + 2 * i + 1)
// marked[j] = true;
//
// primes.push_back(2);
// for (int i = 1; i <= MAX / 2; i++)
// if (marked[i] == false)
// primes.push_back(2 * i + 1);
//}
// Function checks if number is prime //links to showPrimePair
bool isPrime(int n) {
bool prime = true;
for (int i = 2; i <= n / 2; i++)
{
if (n % i == 0) // condition for nonprime number
{
prime = false;
break;
}
}
return prime;
}
// Function for showing prime pairs ( in progress) Integer as a Sum of Two Prime Numbers
bool showPrimePair(int n) {
bool foundPair = true;
for (int i = 2; i <= n / 2; ++i)
// condition for i to be a prime number
{
if (isPrime(i) == 1)
{
// condition for n-i to be a prime number
if (isPrime(n - i) == 1)
{
// n = primeNumber1 + primeNumber2
printf("%d = %d + %d\n", n, i, n - i);
foundPair = true;
break;
}
}
}
if (foundPair == false) {
cout << " Conjecture fails!" << endl;
return 0;
}
}
// Main program in listing conjectures for all even numbers from 4-100,000 along q/ 2 primes that add up to same number.
int main()
{
//sieveSundaram();
cout << "Goldbach's Conjecture by Tony Pham " << endl;
for (int x = 2; x <= MAX; x++) {
/*if (isPrime(x) == true) { //works
cout << x << " is a prime number " << endl;
}
else {
cout << x << " is not a prime number " << endl;
}*/
showPrimePair(x);
}
cout << "Enter any character to quit: ";
cin.get();
}
First you can find all prime numbers in the desired range using the Sieve of Eratosthenes algorithm. Next, you can insert all found primes into a hash set. Finally for each number n in the range you can try all primes p that don't exceed n/2, and probe if the n-p is also a prime (as long as you have a hash set this operation is very fast).
Here is an implementation of Dmitry Kuzminov's answer. It takes a minute to run but it does finish within a reasonable time period. (Also, my implementation skips to the next number if a solution is found, but there are multiple solutions for each number. Finding every solution for each number simply takes WAAAAY too long.)
#include <iostream>
#include <vector>
#include <unordered_set>
std::unordered_set<long long> sieve(long long max) {
auto arr = new long long[max];
std::unordered_set<long long> ret;
for (long long i = 2; i < max; i++) {
for (long long j = i * i; j < max; j+=i) {
*(arr + (j - 1)) = 1;
}
}
for (long long i = 1; i < max; i++) {
if (*(arr + (i - 1)) == 0)
ret.emplace(i);
}
delete[] arr;
return ret;
}
bool is_prime(long long n) {
for(long long i = 2; i <= n / 2; ++i) {
if(n % i == 0) {
return false;
}
}
return true;
}
int main() {
auto primes = sieve(100000);
for (long long n = 4; n <= 100000; n+=2) {
bool found = false;
for (auto prime : primes) {
if (prime <= n / 2) {
if (is_prime(n - prime)) {
std::cout << prime << " + " << n - prime << " = " << n << std::endl;
found = true;
break; // Will move onto the next number after it finds a result
}
}
}
if (!found) { // Replace with whatever code you'd like.
std::terminate();
}
}
}
EDIT: Remember to use delete[] and clean up after ourselves.

C++ Fibonacci Program

C++ Program help
Hello, I am writing a c++ program to print out several fibonacci numbers that are prime. The program prints out 8 numbers but not only those that are prime. Can some please help me find out what is going on
#include <iostream>
#include <cmath>
using namespace std;
//fibonacci function
int fibonacci(int x) {
if ((x == 1) || (x == 2)) { return 1; }
return fib(x - 1) + fib(x - 2);
}
//prime test bool function
bool is_prime(double n) {
for (int i = 2; i <= sqrt(n); i++) {
if (n % i != 0) { return true; }
else { return false; }
}
}
// main function
int main (){
int y = 1;
int c = 0;
while (y >= 0) {
fibonacci(y);
if ((is_prime(true)) && (fibonacci(y) != 1)) {
cout << fib(y) << " ";
count++;
if (c >= 8) { return 0; }
}
y++;
}
}
return 0;
}
Your code above uses double names for the function, and also you use c while you may mean count.
The is_prime function logic should take an int and the function logic is better to be rewritten to look for values that show if the number is not prime.
Lastly, using recursion with Fibonacci function is resource exhaustive. it is better to use plain loops.
check this code against yours:
#include <iostream>
#include <cmath>
using namespace std;
int fib(int x)
{
int first = 0, second = 1, sum = 0;
if ((x == 1) || (x == 2)) { return 1; }
for (int i = 2; i <= x; ++i)
{
sum = first + second;
first = second;
second = sum;
}
return sum;
}
bool is_prime(int n) // n should be int not double
{
for (int i = 2; i <= sqrt(n); i++)
if (n % i == 0)
return false; // you should look for what breaks the condition
return true; // if nothing break the condition you return true
}
int main ()
{
for (int i = 1; i <= 8; ++i)
{
int f = fib(i);
if (is_prime(f))
cout << f << " ";
}
}
Your is_prime() function has a logical problem and appears to be returning the opposite evaluation for input numbers. Try the following:
bool is_prime(int n) {
for (int i=2; i <= sqrt(n); i++) {
// if input divisible by something other than 1 and itself
// then it is NOT prime
if (n % i == 0) {
return false;
}
}
// otherwise it is prime
return true;
}
Here is a demo showing that the refactored is_prime() function is working correctly:
Rextester
Then you can use this function along with your Fibonacci number generator to find say the first 8 prime Fibonacci numbers:
int c = 0;
int y = 1;
do {
int fib = fibonacci(y);
++y;
if (is_prime(fib)) {
cout << fib << " ";
++c;
}
} while (c < 8);
As a side note, your fibonacci() function uses recursion and it won't scale well for large number inputs. Consider using dynamic programming there to dramatically improve performance.
Use Tim Biegeleisen answer for the issues in is_prime() function.
But additionally you do not check your Fibonacci number at all, is_prime is always being called with the same value is_prime(true). And apart of that, in current implementation while cycle will never finish. Try to consider following for the while loop:
while (y >= 0) {
double fib = fibonacci(y);
if ( is_prime(fib) && (fib != 1) ) {
cout << fib << " ";
c++;
if (c >= 8) { return 0; }
}
y++;
}

Determine Amicable Pairs within Confines of Theta(n)

I am attempting to implement a program that reads a positive integer from the user and outputs all the perfect numbers between 2 and userNum. It also outputs all the pairs of amicable numbers that are between 2 and userNum. Both numbers must be within the range. I am seriously struggling with this.
Requirements:
1) calls to AnalyzeDivisors must be kept to theta(userNum) times all together. 2) Function void AnalyzeDivisors must take the following arguments int num, int& outCountDivs, int& outSumDivs. 3) Function bool IsPerfect must take the following argument int num.
I am honestly at a loss for how to do this within that efficiency range. I currently am able to determine all the perfect numbers in the range by bending the rules as far as parameters to the IsPerfect Function, but how can I determine amicable pairs without calling Analyze Dividors an inordinate amount of times each iteration of the for loop in main?
Any help would be greatly appreciated! Code below:
main
int main()
{
int userNum;
//Request number input from the user
cout << "Please input a positive integer num (>= 2): " << endl;
cin >> userNum;
for (int counter = 2; counter <= userNum; counter++)
{
//Set variables
int outCountDivs = 0, outSumDivs = 0, otherAmicablePair = 0;
bool perfectNum = false, isAmicablePair = false;
//Analyze dividors
AnalyzeDividors(counter, outCountDivs, outSumDivs);
//determine perfect num
perfectNum = IsPerfect(counter, outSumDivs);
if (perfectNum)
cout << endl << counter << IS_PERFECT_NUM;
}
return 0;
}
AnalyzeDividors
void AnalyzeDividors(int num, int& outCountDivs, int& outSumDivs)
{
int divisorCounter;
for (divisorCounter = 1; divisorCounter <= sqrt(num); divisorCounter++)
{
if (num % divisorCounter == 0 && num / divisorCounter != divisorCounter && num / divisorCounter != num)
{
//both counter and num/divisorCounter
outSumDivs += divisorCounter + (num / divisorCounter);
outCountDivs += 2;
}
else if ((num % divisorCounter == 0 && num / divisorCounter == divisorCounter) || num/divisorCounter == num)
{
//Just divisorCounter
outSumDivs += divisorCounter;
outCountDivs += 1;
}
}
}
IsPerfect
bool IsPerfect(int userNum, int outSumDivs)
{
if (userNum == outSumDivs)
return true;
else
return false;
}
I think I found a solution that fits the requirements. I found amicable numbers by storing every number and sum of divisors in a map. If a number's sum of divisors is entered in the map, and the sum of divisor's sum of divisors was the current number, then they are amicable.
Because the results are saved each time, you only call AnalyzeDivisors once per number.
Pardon the lazy variable naming.
#include <iostream>
#include <map>
#include <cmath>
void AnalyzeDivisors(int num, int& divc, int &divs)
{
divc = 1;
divs = 1;
for (int x = 2, y = std::sqrt(num); x <= y; ++x)
{
if (num % x == 0)
{
++divc;
divs += x;
if (num / x != x)
{
++divc;
divs += num / x;
}
}
}
}
bool IsPerfect(int num)
{
static std::map<int, int> amicable;
int divc = 0, divs = 0;
AnalyzeDivisors(num, divc, divs);
if (amicable.find(divs) != amicable.end() && amicable[divs] == num)
std::cout << num << " and " << divs << " are best bros for life.\n";
amicable[num] = divs;
return num == divs;
}
int main()
{
int num;
std::cout << "Pick a number: ";
std::cin >> num;
for (int x = 2; x < num; ++x)
{
if (IsPerfect(x))
std::cout << x << " is perfect in every way!\n";
}
}

Count of prime numbers in random sequence (C++)

I have a task to find the count of all prime numbers in random generated sequence.
The input is:
25 10
where 25 is the number s which should be < 10^3 and is used for srand(s) and the number 10 is N(the length of the sequence) which should be < 10^9. The numbers in the sequence are generated with rand()%1000. There are no more than 100 total examples. So here is my code:
#include <iostream>
#include <stdlib.h>
using namespace std;
bool isPrime(int n)
{
if (n == 0 || n == 1) return false;
for (int i = 2; i < n; i++)
{
if (n % i == 0) return false;
}
return true;
}
void Solve(int s, int N)
{
if (s >= 1000 || s <= 0 || N > 1000000000 || N <= 0)
{
cout << "s or N out of bounds!" << endl;
return;
}
int number,
count = 0,
i;
srand(s);
for (i = 1; i <= N; i++)
{
number = rand() % 1000;
if (isPrime(number))
{
count++;
}
}
cout << count << endl;
}
int main()
{
int s, N;
int counter = 0;
while (cin >> s >> N)
{
if (++counter == 100)
{
cout << "You have reached the maximum examples(100)!" << endl;
break;
}
Solve(s, N);
}
return 0;
}
And when I input 25 10 the answer should be 3 but I got 1. Where is my problem? Any help will be appreciated.