How could I find the biggest common divisor of 2 numbers using array? I tried to solve it using 2 arrays and I couldn't finish it. How could I improve this program?
#include <iostream>
using namespace std;
int main()
{
unsigned int A[2][10], B[2][10], a, b, c_exp, d, i1, P, x;
bool apartine = false;
cout << "a="; cin >> a;
cout << "b="; cin >> b;
P = 1;
c_exp = 0;
i1 = 0;
while (a % 2 == 0)
{
c_exp++;
a = a/2;
}
if (c_exp != 0)
{
A[i1][0] = 2;
A[i1][1] = c_exp;
i1++;
}
d = 3;
while (a != 1 && d <= a)
{
c_exp=0;
while (a % d == 0)
{
c_exp++;
a = a/d;
}
if (c_exp!=0)
{
A[i1][0] = d;
A[i1][1] = c_exp;
i1++;
}
d = d+2;
}
cout << "\nMatricea A contine:";
for (int i = 0; i < i1; i++)
{
cout << "\n";
for (int j = 0; j < 2; j++)
cout << A[i][j] << ",";
}
c_exp = 0;
i1 = 0;
while (b % 2 == 0)
{
c_exp++;
b = b/2;
}
if (c_exp != 0)
{
B[i1][0] = 2;
B[i1][1] = c_exp;
i1++;
}
d = 3;
while (b != 1 && d <= b)
{
c_exp = 0;
while (b % d == 0)
{
c_exp++;
b = b/d;
}
if (c_exp != 0)
{
B[i1][0] = d;
B[i1][1] = c_exp;
i1++;
}
d = d+2;
}
cout << "\nMatricea B contine:";
for (int i = 0; i < i1; i++)
{
cout << "\n";
for (int j = 0; j < 2; j++)
cout << B[i][j] << ",";
}
return 0;
}
From now on I have to find if the first number of first array exist in the second array and after this I have to compare the exponents of the same number of both array and the lowest one I have to add it to product. After this I have to repeat the same proccess with the second number to the last one of the first array. The problem is that I don't know how to write this.I have to mention that this program isn't complete.
Any ideas?
If you need better solution then you can avoid array and use the below logic.
int main()
{
int a =12 ,b = 20;
int min = a>b ? a:b; // finding minimum
if(min > 1)
{
for (int i=min/2; i>1; i--)//Reverse loop from min/2 to 1
{
if(a%i==0 && b%i==0)
{
cout<<i;
break;
}
}
}
else if(min == 1)
{
cout<<"GCD is 1";
}
else
cout<<"NO GCD";
return 0;
}
You can also check the working example Greatest Common Divisor
I am not quite sure what you are trying to achieve with your code. It looks over complicated. If I were to find the biggest common divisor of two numbers I would do something like the following:
## This is not a correct implementation in C++ (but close to it) ##
Read the two integers **a** and **b**
int max_div(int a, int b){
int div = a > b ? a : b;
while (div != 1 && (a%div != 0 && b%div != 0)){
div--;
}
return div;
}
This function starts with the minimum of a and b as the highest possible common divisor and then works its way backwards until one of two possible outcomes:
It finds a common divisor (a%div == 0 and b%div == 0)
It reaches one (always a common divisor)
EDIT : Now returns one if no higher divisor is found. (Was returning zero which made no sense)
Related
Recently I've been working on this problem on SPOJ:
Given a set of N integers A = {1, 2, 3, …, N} and an integer S, your task is find a way to insert an operator '+' or '-' to every neighbor pair of A, that the result of the expression after insert equal to S.
WARNING: You can't put any operators in front of 1.
Input:
A single line, including N and S (1 ≤ N ≤ 500, |S| ≤ 125250)
Output:
If there are way(s) to insert, output any of them, otherwise output “Impossible” (without quotes).
Example:
Input:
9 5
Output:
1-2+3-4+5-6+7-8+9
Input:
5 6
Output:
Impossible
I've already been messing up with these code, but SPOJ always yields that I've done this problem in the wrong way. I think there might be exceptions that I haven't found out.
int main()
{
int n;
cin >> n;
int a[501] = { };
int sum = 0;
for (int i = 1; i <= n; i++)
{
a[i] = 1;
sum += i;
}
int s;
cin >> s;
int aim = sum - s;
if ((aim % 2 != 0) || (s < -sum + 2) || (s > sum) || (s == -sum + 4) || (s == sum - 1))
{
cout << "Impossible" << endl;
return 0;
}
int c = n;
while (aim != 0)
{
if (aim >= c)
{
if (aim - 2 * c != 2)
{
aim -= (2 * c);
a[c] = -1;
c--;
}
else
{
a[c - 1] = -1;
a[2] = -1;
aim -= (2 * c + 2);
}
}
else
{
a[aim / 2] = -1;
aim = 0;
}
}
for (int i = 1; i <= n; i++)
if (a[i] == 1)
if (i == 1)
cout << i;
else
cout << "+" << i;
else
cout << "-" << i;
return 0;
}
You are subtracting 2 * c from aim after checking if aim >= c.
Changing the check to aim >= 2 * c will improve your program.
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'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)
#include <cstdlib>
#include <iostream>
#include <Math.h>
#include <algorithm>
#include <string>
#include <iterator>
#include <iostream>
#include <vector> // std::vector
using namespace std;
int stepCount, i, x, y, z, j, k, array1Size, array2Size, tester, checker;
int numstring[10] = { 0,1,2,3,4,5,6,7,8,9 };
int numstringTest[10] = { 0,1,2,3,4,5,6,7,7,9 };
int* numbers;
int* differentNumbers;
int* p;
int* otherNumbers;
void stepCounter(int a) {
// determines the step number of the number
if (a / 10 == 0)
stepCount = 1;
else if (a / 100 == 0)
stepCount = 2;
else if (a / 1000 == 0)
stepCount = 3;
else if (a / 10000 == 0)
stepCount = 4;
else if (a / 100000 == 0)
stepCount = 5;
else if (a / 1000000 == 0)
stepCount = 6;
else if (a / 10000000 == 0)
stepCount = 7;
else if (a / 100000000 == 0)
stepCount = 8;
else if (a / 1000000000 == 0)
stepCount = 9;
}
void stepIndicator(int b) {
// indicates each step of the number and pass them into array 'number'
stepCounter(b);
numbers = new int[stepCount];
for (i = stepCount; i>0; i--) {
//
/*
x = (round(pow(10,stepCount+1-i)));
y = (round(pow(10,stepCount-i)));
z = (round(pow(10,stepCount-i)));
*/
x = (int)(pow(10, stepCount + 1 - i) + 0.5);
y = (int)(pow(10, stepCount - i) + 0.5);
numbers[i - 1] = (b%x - b%y) / y;
}
}
int sameNumberCheck(int *array, int arraySize) {
//checks if the array has two or more of same integer inside return 1 if same numbers exist, 0 if not
for (i = 0; i<arraySize - 1; i++) {
//
for (j = i + 1; j<arraySize; j++) {
//
if (array[i] == array[j]) {
//
return 1;
}
}
}
return 0;
}
void getDifferentNumbers(int* array, int arraySize) {
//
k = 0;
j = 0;
checker = 0;
otherNumbers = new int[10 - arraySize]; //exact number of other numbers is 10 - numbers we have
for (i = 0; i<10; i++) {
if ((i>0)&(checker = 0)) {
k++;
otherNumbers[k - 1] = i - 1;
}
//
checker = 0;
for (j = 0; j<arraySize; j++) {
//
p = array + j;
cout << *p << endl; //ilkinde doğru sonra yanlış yapıyor?!
if (*p = i) {
checker++;
}
}
}
}
int main(int argc, char *argv[])
{
stepCounter(999999);
cout << stepCount << endl;
stepIndicator(826424563);
for (j = 0; j<9; j++) {
//
cout << numbers[j] << endl;
}
cout << sameNumberCheck(numstringTest, 10) << " must be 1" << endl;
cout << sameNumberCheck(numstring, 10) << " must be 0" << endl;
cout << endl;
getDifferentNumbers(numstringTest, 10);
cout << endl;
cout << endl << otherNumbers[0] << " is the diff number" << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
Hi, my problem is with pointers actually. You will see above, function getDifferentNumbers. It simply does a comparement if in any given array there are repeated numbers(0-9). To do that, I passed a pointer to the function. I simply do the comparement via pointer. However, there is a strange thing here. When I execute, first time it does correct, but secon time it goes completely mad! This is the function:
void getDifferentNumbers(int* array, int arraySize) {
//
k = 0;
j = 0;
checker = 0;
otherNumbers = new int[10 - arraySize]; //exact number of other numbers is 10 - numbers we have
for (i = 0; i<10; i++) {
if ((i>0)&(checker = 0)) {
k++;
otherNumbers[k - 1] = i - 1;
}
//
checker = 0;
for (j = 0; j<arraySize; j++) {
//
p = array + j;
cout << *p << endl; //ilkinde doğru sonra yanlış yapıyor?!
if (*p = i) {
checker++;
}
}
}
}
and this is the array I passed into the function:
int numstringTest[10] = {0,1,2,3,4,5,6,7,7,9};
it should give the number 7 in otherNumbers[0], however it does not. And I do not know why. I really can not see any wrong statement or operation here. When I execute, it first outputs the correct values of
numstringTest: 1,2,3,4,5,6,7,7,9
but on next 9 iteration of for loop it outputs:
000000000011111111112222222222333333333344444444445555555555666666666677777777778888888888
You have some basic problems in your code.
There are multiple comparisons that are not really comparisons, they're assignments. See the following:
if((i>0) & (checker=0)){
and
if(*p = i){
In both cases you're assigning values to the variables, not comparing them. An equality comparison should use ==, not a single =. Example:
if (checker == 0) {
Besides that, you're using & (bitwise AND) instead of && (logical AND), which are completely different things. You most likely want && in your if statement.
I've just noticed this:
getDifferentNumbers(numstringTest, 10);
and in that function:
otherNumbers = new int[10 - arraySize];
which doesn't seem right.
I'm trying to print all common multiples of two integers smaller than a certain limit(100 in my case). However, when I call my function, it does nothing. This is my code:
void com_mul(int a, int b)
{
int original = b;
for(int i = 1; a <= 100; i++)
{
a *= i;
b = original;
for(int j = 1; b <= a; j++)
{
b *= j;
if(a == b)
cout << b << ", ";
}
}
}
You can solve this problem much simpler, using a single loop.
In a for loop iterate over potential divisors d from 1 to 100. If d divides both a and b, print d.
You can tell if a number divides another number by applying the % operator, and checking the result for zero:
if (a%d == 0 && b%d == 0) {
cout << d << endl;
}
Tested with a = 4, b = 2, max = 100 on my machine. And it outputs 4.
This is because of the line for (int j = 1; b <= a; j++). j can only go upto 'a'
I think this would do.
#include <iostream>
#include <string>
int main()
{
int a, b, max;
std::cin >> a >> b >> max;
for (int i = a; i <= max; i++)
{
if (i%a == 0 && i%b == 0)
std::cout << i << std::endl;
}
return 0;
}