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;
}
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;
}
a beginner at coding here.
I was practising loops(c++) when I stumbled upon this problem:-
Write a program in C++ to find the perfect numbers between 1 and 500. (6,28 and 496)
Perfect number: It is a positive integer that is equal to the sum of its proper divisors. The smallest perfect number is 6, which is the sum of 1, 2, and 3.
I wrote the following code:-
#include <iostream>
using namespace std;
int main() {
int n=2; //test numbers from 2 to 500.
int div=1; //divisor for n.
int sum=0; //sum of divisors which divide n.
while (n<=500) {
while (div<n){ //if div divides n, then it will added to sum and incremented, else only incremented.
if (n%div==0){
sum=sum+div;
div++;
} else{
div++;
}
}
if (sum==n){
cout<<n<<" is a perfect number."<<endl;
n++;
} else{
n++;
}
}
return 0;
}
The code is supposed to print that 6, 28 and 496 are perfect numbers.
But instead, it's not printing anything. Haven't been able to find the error yet after checking for 30+ minutes.
Could anyone point out the error?
You forget to re-initialize some variables in your loop.
for seems more appropriate than while here.
Create sub function also help to "identify" scope.
#include <iostream>
bool isPerfectNumber(int n)
{
int sum = 0;
for (int div = 1; div != n; ++div) {
if (n % div == 0) {
sum += div;
}
}
return sum == n && n > 0;
}
int main()
{
for (int i = 2; i != 501; ++i) {
if (isPerfectNumber(i)) {
std::cout << n << " is a perfect number." << std::endl;
}
}
return 0;
}
#include<iostream>
using namespace std;
bool perfect_num(int x);
int main() {
int m, n, x;
cout << "input the range m, n: " << "\n";
cin >> m >> n;
for (x = m; x <= n; ++x) {
if (perfect_num(x)) {
cout << x << " ";
}
}
return 0;
}
bool perfect_num(int x) {
bool flag = false;
//initialize
int sum = 0, i;
//loop 1 to x
for (i = 1; i < x; ++i) {
//judge whether is the factor
if (x % i == 0) {
sum += i;
}
}
//update flag
flag = (sum == x);
return flag;
}
#include<iostream>
using namespace std;
//judge function
bool isPerfectNum(int num){
int tmp = 0;
for (int i = 1; i < num; ++i) {
if (num % i == 0) {
tmp += i;
}
}
return tmp == num;
}
int main(){
cout << "Perfect Number contains: ";
for (int i = 1; i <= 500; ++i){
if (isPerfectNum(i)) {
cout << i << " ";
}
}
cout << "\n";
return 0;
}
at the end of your first loop, you should bring back div and sum to their default value.
int main() {
int n=2; //test numbers from 2 to 500.
int div=1; //divisor for n.
int sum=0; //sum of divisors which divide n.
while (n<=500) {
while (div<n){ //if div divides n, then it will added to sum and incremented, else only incremented.
if (n%div==0){
sum=sum+div;
div++;
} else{
div++;
}
}
if (sum==n){
cout<<n<<" is a perfect number."<<endl;
n++;
} else{
n++;
}
div = 1; // you should bring them back here.
sum = 0;
}
return 0;
}
Homework: I'm just stumped as hell. I have algorithms set up, but I have no idea how to code this
Just to be clear you do not need arrays or to pass variables by reference.
The purpose of the project is to take a problem apart and using Top-Down_Design or scratch pad method develop the algorithm.
Problem:
Examine the numbers from 2 to 10000. Output the number if it is a Dual_Prime.
I will call a DualPrime a number that is the product of two primes. Ad where the two primes are not equal . So 9 is not a dual prime. 15 is ( 3 * 5 ) .
The output has 10 numbers on each line.
My Algorithm set-up
Step 1: find prime numbers.:
bool Prime_Number(int number)
{
for (int i = 2; i <= sqrt(number); i++)
{
if (number % 1 == 0)
return false;
}
return true;
}
Step 2: store prime numbers in a array
Step 3: Multiply each array to each other
void Multiply_Prime_Numbers(int Array[], int Size)
{
for (int j = 0; j < Size- 1; j++)
{
Dual_Prime[] = Arr[j] * Arr[j + 1]
}
}
Step 4: Bubble sort
void Bubble_Sort(int Array[], int Size) // Sends largest number to the right
{
for (int i = Size - 1; i > 0; i--)
for (int j = 0; j < i; j++)
if (Array[j] > Array[j + 1])
{
int Temp = Array[j + 1];
Array[j + 1] = Array[j];
Array[j] = Temp;
}
}
Step 5: Display New Array by rows of 10
void Print_Array(int Array[], int Size)
{
for (int i = 0; i < Size; i++)
{
cout << Dual_Prime[i] << (((j % 10) == 9) ? '\n' : '\t');
}
cout << endl;
}
I haven't learned dynamic arrays yet,
Although dynamic arrays and the sieve of Eratosthenes are more preferable, I tried to write minimally fixed version of your code.
First, we define following global variables which are used in your original implementation of Multiply_Prime_Numbers.
(Please check this post.)
constexpr int DP_Size_Max = 10000;
int DP_Size = 0;
int Dual_Prime[DP_Size_Max];
Next we fix Prime_Number as follows.
The condition number%1==0 in the original code is not appropriate:
bool Prime_Number(int number)
{
if(number<=1){
return false;
}
for (int i = 2; i*i <= number; i++)
{
if (number % i == 0)
return false;
}
return true;
}
In addition, Multiply_Prime_Numbers should be implemented by double for-loops as follows:
void Multiply_Prime_Numbers(int Array[], int Size)
{
for (int i = 0; i < Size; ++i)
{
for (int j = i+1; j < Size; ++j)
{
Dual_Prime[DP_Size] = Array[i]*Array[j];
if(Dual_Prime[DP_Size] >= DP_Size_Max){
return;
}
++DP_Size;
}
}
}
Then these functions work as follows.
Here's a DEMO of this minimally fixed version.
int main()
{
int prime_numbers[DP_Size_Max];
int size = 0;
for(int j=2; j<DP_Size_Max; ++j)
{
if(Prime_Number(j)){
prime_numbers[size]=j;
++size;
}
}
Multiply_Prime_Numbers(prime_numbers, size);
Bubble_Sort(Dual_Prime, DP_Size);
for(int i=0; i<DP_Size;++i){
std::cout << Dual_Prime[i] << (((i % 10) == 9) ? '\n' : '\t');;
}
std::cout << std::endl;
return 0;
}
The Sieve of Eratosthenes is a known algorithm which speeds up the search of all the primes up to a certain number.
The OP can use it to implement the first steps of their implementation, but they can also adapt it to avoid the sorting step.
Given the list of all primes (up to half the maximum number to examine):
Create an array of bool as big as the range of numbers to be examined.
Multiply each distinct couple of primes, using two nested loops.
If the product is less than 10000 (the maximum) set the corrisponding element of the array to true. Otherwise break out the inner loop.
Once finished, traverse the array and if the value is true, print the corresponding index.
Here there's a proof of concept (implemented without the OP's assignment restrictions).
// Ex10_TwoPrimes.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void Homework_Header(string Title);
void Do_Exercise();
void Sieve_Of_Eratosthenes(int n);
void Generate_Semi_Prime();
bool Semi_Prime(int candidate);
bool prime[5000 + 1];
int main()
{
Do_Exercise();
cin.get();
return 0;
}
void Do_Exercise()
{
int n = 5000;
Sieve_Of_Eratosthenes(n);
cout << endl;
Generate_Semi_Prime();
}
void Sieve_Of_Eratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
memset(prime, true, sizeof(prime));
for (int p = 2; p*p <= n; p++)
{
// If prime[p] is not changed, then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
bool Semi_Prime(int candidate)
{
for (int index = 2; index <= candidate / 2; index++)
{
if (prime[index])
{
if (candidate % index == 0)
{
int q = candidate / index;
if (prime[q] && q != index)
return true;
}
}
}
return false;
}
void Generate_Semi_Prime()
{
for (int i = 2; i <= 10000; i++)
if (Semi_Prime(i)) cout << i << "\t";
}
I'm trying to get all prime numbers in the range of 2 and the entered value using this c++ code :
#include<iostream>
using namespace std;
int main() {
int num = 0;
int result = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
for (int b = 2; b <= num; b++) {
result = i % b;
if (result == 0) {
result = b;
break;
}
}
cout << result<< endl <<;
}
}
the problem is that I think am getting close to the logic, but those threes and twos keep showing up between the prime numbers. What am I doing wrong?
I've fixed your code and added comments where I did the changes
The key here is to understand that you need to check all the numbers smaller then "i" if one of them dividing "i", if so mark the number as not prime and break (the break is only optimization)
Then print only those who passed the "test" (originally you printed everything)
#include <iostream>
using namespace std;
#include<iostream>
using namespace std;
int main()
{
int num = 0;
int result = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
bool isPrime = true; // Assume the number is prime
for (int b = 2; b < i; b++) { // Run only till "i-1" not "num"
result = i % b;
if (result == 0) {
isPrime = false; // if found some dividor, number nut prime
break;
}
}
if (isPrime) // print only primes
cout << i << endl;
}
}
Many answers have been given which explains how to do it. None have answered the question:
What am I doing wrong?
So I'll give that a try.
#include<iostream>
using namespace std;
int main() {
int num = 0;
int result = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
for (int b = 2; b <= num; b++) { // wrong: use b < i instead of b <= num
result = i % b;
if (result == 0) {
result = b; // wrong: why assign result the value of b?
// just remove this line
break;
}
}
cout << result<< endl <<; // wrong: you need a if-condtion before you print
// if (result != 0) cout << i << endl;
}
}
You have multiple errors in your code.
Simplest algorithm (not the most optimal though) is for checking whether N is prim is just to check whether it doesn't have any dividers in range [2; N-1].
Here is working version:
int main() {
int num = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
bool bIsPrime = true;
for (int b = 2; bIsPrime && b < i; b++) {
if (i % b == 0) {
bIsPrime = false;
}
}
if (bIsPrime) {
cout << i << endl;
}
}
}
I would suggest pulling out the logic of determining whether a number is a prime to a separate function, call the function from main and then create output accordingly.
// Declare the function
bool is_prime(int num);
Then, simplify the for loop to:
for (int i = 2; i <= num; i++) {
if ( is_prime(i) )
{
cout << i << " is a prime.\n";
}
}
And then implement is_prime:
bool is_prime(int num)
{
// If the number is even, return true if the number is 2 else false.
if ( num % 2 == 0 )
{
return (num == 2);
}
int stopAt = (int)sqrt(num);
// Start the number to divide by with 3 and increment it by 2.
for (int b = 3; b <= stopAt; b += 2)
{
// If the given number is divisible by b, it is not a prime
if ( num % b == 0 )
{
return false;
}
}
// The given number is not divisible by any of the numbers up to
// sqrt(num). It is a prime
return true;
}
I can pretty much guess its academic task :)
So here the think for prime numbers there are many methods to "get primes bf number" some are better some worse.
Erosthenes Sieve - is one of them, its pretty simple concept, but quite a bit more efficient in case of big numbers (like few milions), since OopsUser version is correct you can try and see for yourself what version is better
void main() {
int upperBound;
cin >> upperBound;
int upperBoundSquareRoot = (int)sqrt((double)upperBound);
bool *isComposite = new bool[upperBound + 1]; // create table
memset(isComposite, 0, sizeof(bool) * (upperBound + 1)); // set all to 0
for (int m = 2; m <= upperBoundSquareRoot; m++) {
if (!isComposite[m]) { // if not prime
cout << m << " ";
for (int k = m * m; k <= upperBound; k += m) // set all multiplies
isComposite[k] = true;
}
}
for (int m = upperBoundSquareRoot; m <= upperBound; m++) // print results
if (!isComposite[m])
cout << m << " ";
delete [] isComposite; // clean table
}
Small note, tho i took simple implementation code for Sive from here (writing this note so its not illegal, truth be told wanted to show its easy to find)
I'm trying to modify this program to their equivalent iterative but it becomes very difficult to me because as yet i'm still a newbie, it comes to an algorithm that decomposes a number into its prime factors, here the code:
#include <iostream>
#include <map>
#include <cmath>
std::map< int, std::pair<int, int> > decompositions;
void descompon_number(int num, int root, int i = 2 )
{
auto iterator = decompositions.find(num);
if (iterator == decompositions.end())
{
if (num > 1 && i <= root)
{
if (num % i == 0)
{
int n = num / i;
decompositions[num] = std::make_pair(i, n);
descompon_number(n, (int) std::sqrt(n));
}
else
descompon_number(num, root, i + 1);
}
else
decompositions[num] = std::make_pair(num, 1);
}
}
void show(int num, int factor, int exponent, int see)
{
auto pair = decompositions[num];
if (num <= 1 || factor != pair.first)
{
if (see)
std::cout << factor;
if (exponent > 1 && see)
std::cout << "^" << exponent;
if (pair.first > 1 && see)
std::cout << " * ";
exponent = 0;
}
if (num > 1)
show(pair.second, pair.first, exponent + 1, see);
}
void descompon(int a, int b, int see)
{
if (a <= b)
{
descompon_number(a, (int) std::sqrt(a));
if (see)
std::cout << a << " = ";
show(a, decompositions[a].first, 0, see);
if (see)
std::cout << std::endl;
descompon(a + 1, b, see);
}
}
int main()
{
descompon(2, 100, 1);
return 0;
}
Someone can help me out with this
Finding prime factors iteratively is not very complicated.
Here's the pseudocode how to do this.
Let P be a list of the first n prime numbers, such that Pn <= sqrt(m).
array findPrimeFactors(m)
answer = new array
for p in P
while m can be divided by p
m = m / p
answer.append(p)
if m == 1
break
return answer
Note: empty array is returned if m is prime.
You can use an erastotenes' sieve to compute prime numbers, and later you can use the algorithm posted by popovitsj.
The following code can be optimized, but its main purpose is to show you how to proceed.
Complete example:
#include <iostream>
#include <vector>
using namespace std;
// Returns a vector containing the first <number> prime numbers
vector<int> erastotenes_sieve(int number)
{
vector<int> result;
int *sieve = new int[number];
for (int i = 0; i < number; i++) sieve[i] = 0;
// Traverse the sieve marking multiples.
for (int i = 2; i < number / 2; i++)
for (int j = i + i; j < number; j += i)
sieve[j] = 1;
// Collect unaffected indexes, those are prime numbers.
for (int i = 2; i < number; i++)
if (!sieve[i])
result.push_back(i);
delete [] sieve;
return result;
}
vector<int> descompon_number(int number)
{
vector<int> result;
if (number == 1 || number == 0)
{
result.push_back(number);
return result;
}
for (int &prime : erastotenes_sieve(number))
{
while (number % prime == 0 && number != 1)
{
number /= prime;
result.push_back(prime);
}
}
return result;
}
int main()
{
for (auto &i : descompon_number(20))
{
cout << i << endl;
}
return 0;
}