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.
Related
So far I have this code. I'm trying to print prime factorization with exponents. For example, if my input is 20, the output should be 2^2, 5
#include <iostream>
#include <cmath>
using namespace std;
void get_divisors (int n);
bool prime( int n);
int main(int argc, char** argv) {
int n = 0 ;
cout << "Enter a number and press Enter: ";
cin >>n;
cout << " Number n is " << n << endl;
get_divisors(n);
cout << endl;
return 0;
}
void get_divisors(int n){
double sqrt_of_n = sqrt(n);
for (int i =2; i <= sqrt_of_n; ++i){
if (prime (i)){
if (n % i == 0){
cout << i << ", ";
get_divisors(n / i);
return;
}
}
}
cout << n;
}
bool prime (int n){
double sqrt_of_n = sqrt (n);
for (int i = 2; i <= sqrt_of_n; ++i){
if ( n % i == 0) return 0;
}
return 1;
}
I hope someone can help me with this.
You can use an std::unordered_map<int, int> to store two numbers (x and n for x^n). Basically, factorize the number normally by looping through prime numbers smaller than the number itself, dividing the number by the each prime as many times as possible, and recording each prime you divide by. Each time you divide by a prime number p, increment the counter at map[p].
I've put together a sample implementation, from some old code I had. It asks for a number and factorizes it, displaying everything in x^n.
#include <iostream>
#include <unordered_map>
#include <cmath>
bool isPrime(const int& x) {
if (x < 3 || x % 2 == 0) {
return x == 2;
} else {
for (int i = 3; i < (int) (std::pow(x, 0.5) + 2); i += 2) {
if (x % i == 0) {
return false;
}
}
return true;
}
}
std::unordered_map<int, int> prime_factorize(const int &x) {
int currentX = abs(x);
if (isPrime(currentX) || currentX < 4) {
return {{currentX, 1}};
}
std::unordered_map<int, int> primeFactors = {};
while (currentX % 2 == 0) {
if (primeFactors.find(2) != primeFactors.end()) {
primeFactors[2]++;
} else {
primeFactors[2] = 1;
}
currentX /= 2;
}
for (int i = 3; i <= currentX; i += 2) {
if (isPrime(i)) {
while (currentX % i == 0) {
if (primeFactors.find(i) != primeFactors.end()) {
primeFactors[i]++;
} else {
primeFactors[i] = 1;
}
currentX /= i;
}
}
}
return primeFactors;
}
int main() {
int x;
std::cout << "Enter a number: ";
std::cin >> x;
auto factors = prime_factorize(x);
std::cout << x << " = ";
for (auto p : factors) {
std::cout << "(" << p.first << " ^ " << p.second << ")";
}
}
Sample output:
Enter a number: 1238
1238 = (619 ^ 1)(2 ^ 1)
To begin with, avoid using namespace std at the top of your program. Second, don't use function declarations when you can put your definitions before the use of those functions (but this may be a matter of preference).
When finding primes, I'd divide the number by 2, then by 3, and so on. I can also try with 4, but I'll never be able to divide by 4 if 2 was a divisor, so non primes are automatically skipped.
This is a possible solution:
#include <iostream>
int main(void)
{
int n = 3 * 5 * 5 * 262417;
bool first = true;
int i = 2;
int count = 0;
while (i > 1) {
if (n % i == 0) {
n /= i;
++count;
}
else {
if (count > 0) {
if (!first)
std::cout << ", ";
std::cout << i;
if (count > 1)
std::cout << "^" << count;
first = false;
count = 0;
}
i++;
if (i * i > n)
i = n;
}
}
std::cout << "\n";
return 0;
}
Note the i * i > n which is an alternative to the sqrt() you are using.
Given an array of integers and a number k, write a function that returns true if given array can be divided into pairs such that sum of every pair is divisible by k.
This code is producing correct results for all test cases except one I cannot find the glitch in it.
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int k;
cin >> k;
int flag[n] = {0};
int p = 0;
int q = 0;
if (n % 2 != 0) {
cout << "False" << endl;
} else {
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if ((arr[i] + arr[j]) % k == 0 && flag[j] == 0) {
p = 1;
flag[j] = 1;
}
}
if (p == 0) {
q = 1;
cout << "False" << endl;
break;
}
}
if (q == 0) {
cout << "True" << endl;
}
}
}
return 0;
}
One of the big sources of bugs in code is messy code. So how do we clean up code? We modularize it. This means breaking up the code so that each portion of the code does one job well. Let's see what that looks like.
Function to check if something is divisible by k:
bool isDivisible(int number, int divisor) {
return number % divisor == 0;
}
Function to check all pairs:
The logic is as follows:
Take the first number in the list; call in n0.
For every remaining number n1, check if that plus the first number is divisible by k
When we find n1 such that n0 + n1 is divisible by k,
a. If the remaining numbers left over can also be split into divisible pairs, return true
b. Otherwise, continue searching
4.If we've searched through all the numbers, return false.
bool pairsDivisible(int* nums, int count, int k) {
if(count == 0) return true;
if(count % 2 != 0) return false; // count must be even
// 1.
int n0 = nums[0];
// 2.
for(int i = 1; i < count; i++) {
int n1 = nums[i];
// 3.
if(isDivisible(n0 + n1, k)) {
// Move the ith number so it's now nums[1]
std::swap(nums[1], nums[i]);
if(pairsDivisible(nums + 2, count - 2, k)) {
return true; // 3.a
} else {
// Reset the array
std::swap(nums[1], nums[i]);
}
}
}
return false;
}
I need to find the sum of prime numbers between two numbers, say x1 and x2 inclusively, however i cant detect whats wrong?
for example if i entered 3 and 9 i would get 15 but i am getting 133!
#include <iostream>
using namespace std;
int prime(int n1, int n2)
{
int count =0;
bool prime = true;
for (n1; n1 < n2; n1++)
{
for (int i = 2; i < n1; i++)
{
if (n1 % i == 0) {
prime = false;
continue;
}
else
count++;
}
}
return count;
}
int main()
{
int n1, n2;
cout << " Enter values for n1 and n2 (n1 must be smaller than n2): ";
cin >> n1>>n2;
cout << " Sum of prime numbers from " << n1 << " and till " << n2 << " inclusively : " << prime(n1, n2) << endl;
system("pause");
return 0;
}
Your prime function is not appropriate. This should be like.
int prime(int n1, int n2) {
int sum = 0;
for (n1; n1 < n2; n1++) {
bool prime = true;
for (int i = 2; i < n1; i++) {
if (n1 % i == 0) {
prime = false;
break;
}
}
if( prime ) { // current n1 is prime
sum = sum + n1;
}
}
return sum;
}
You are not adding anything if your n1 is prime.
I am a big believer in the one loop per function. This is a very good example for this. Your inner loop checks if a number is prime so really it should be a function on its own:
bool is_prime(int n);
int sum_primes_between(int n1, int n2)
{
int sum = 0;
for (; n1 <= n2; n1++)
{
if (is_prime(n1))
sum += n1;
}
return count;
}
Now not only it's easier to read, but you can better test individual parts of code. You can test that is_prime is correct and after that you can test num_primes_between is correct. If you had gone this route from the start you wouldn't even have had the bug you currently have with detecting if a number is prime.
And here is an even neater solution with range-v3:
using namespace ranges;
bool is_prime(int n);
int sum_primes_between(int n1, int n2)
{
return accumulate(view::ints(n1, n2 + 1) | view::filter(is_prime), 0);
}
None of the answers provided so far respect the requirement of being inclusive.
Here's a corrected version including an optimized algorithm to check for primality:
#include <iostream>
#include <cmath>
using namespace std;
bool is_prime(int n) {
// handle special cases
if (n <= 1) {
return false;
}
if (n <= 3) {
return true;
}
if (n % 2 == 0 || n % 3 == 0) {
return false;
}
/* because we covered multiples of 2 and 3 we can reduce the number of checks
drastically */
for(int i = 5, r = sqrt(n); i =< r; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
int sum_of_primes(int n1, int n2) {
int sum = 0;
// loop from n1 up to n2
for ( ;n1 <= n2; n1++) {
if (is_prime(n1)) {
sum += n1;
}
}
return sum;
}
int main() {
cout<<"The sum of primes between 2 and 15 is: "<<sum_of_primes(2,15)<<endl;
return 0;
}
Your original code didn't calculate the sum of primes, you simply incremented your count variable on every iteration that didn't find a divisor of the current number you were checking.
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.
I'm trying to write a function that would return a prime factorisation of a given number (as part of solving project euler's problem #12). To count the prime factors. I use std::map.
The code is as follows:
#include "stdafx.h"
#include <iostream>
#include <map>
#include <algorithm>
bool IsPrime(unsigned int number)
{
if (number < 1) return 0; // zero is not prime. For our purposes, one would be.
for (unsigned int i = 2; i*i <= number; ++i)
{
if (number % i == 0)
return false;
}
return true;
}
int divisors(unsigned int num)
{
int orig_num = num;
std::map <int, int> primefactors;
for(unsigned int i = 1; i <= num; ++i)
if (num % i == 0 && IsPrime(i))
{
num /= i;
++primefactors[i];
std::cout << primefactors[i] << "\t";
}
std::cout << orig_num << " = ";
for(auto& iter:primefactors)
std::cout << iter.first << "^" << iter.second << " * ";
return 0;
}
int main()
{
divisors(661500);
return 0;
}
The problem is that all the counts of primefactors are returned as 1s, although the number in main was chosen specifically to be a product of primes to larger than 1 powers (661500 = 1^1*2^2*3^3*5^3*7^2).
My guess is that I'm incrementing something wrong.
You are dividing only once per prime. But you should continue dividing by the prime as long as number is divisible by it:
for(unsigned int i = 2; i <= num; ++i)
if (IsPrime(i))
{
while (num % i == 0) {
num /= i;
++primefactors[i];
std::cout << primefactors[i] << "\t";
}
}
Actually there is no need for IsPrime(i) condition:
for(unsigned int i = 2; i <= num; ++i)
while (num % i == 0) {
num /= i;
++primefactors[i];
std::cout << primefactors[i] << "\t";
}
Proof: if i is not a prime, then condition num % i == 0 implies that num is divisible by a prime factor p of i. But p < i so our loop had to go through p some time before i. And while loop would effectively erase all occurences of p in num. In particular by the time that for reaches i we have that num is no longer divisible by p. Contradiction. I.e. in the loop above if num % i == 0 is satisfied, then i is prime.