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;
}
Related
program asked is sum of digits :
Input data are in the following format:
first line contains N - the number of values to process;
and then N lines will follow describing the values for which sum of digits should be calculated by 3 integers A B C;
for each case you need to multiply A by B and add C (i.e. A * B + C) - then calculate sum of digits of the result.
Answer should have N results, also separated by spaces
MY CODE IN C++ :
#include <iostream>
using namespace std;
int main ()
{
int n, a, b, c, t, sum = 0;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a >> b >> c;
t = a * b + c;
while (t % 10 != 0)
{
sum = sum + t % 10;
t = t / 10;
}
while (t % 10 == 0)
{
sum = sum;
t = t / 10;
}
}
cout << " ";
cout << sum;
cout << " ";
return 0;
}
I'm having hard time correcting my code.
Any help is appreciated.
My assumption is there should be a better way to code this other than using 2 while loops.
PS : I checked other topics just want somebody that could help with my code thank you.
You don't need second while loop, and first one should be corrected to while (t != 0). After that your program for computing sum works correctly.
Try it online!
#include <iostream>
using namespace std;
int main ()
{
int n, a, b, c, t, sum = 0;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a >> b >> c;
t = a * b + c;
while (t != 0)
{
sum = sum + t % 10;
t = t / 10;
}
}
cout << " ";
cout << sum;
cout << " ";
return 0;
}
Input:
1
123 456 789
Output:
33
Just noticed that you need N separate outputs instead of single sum (like you did), so then your program becomes like this:
Try it online!
#include <iostream>
using namespace std;
int main ()
{
int n, a, b, c, t, sum = 0;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a >> b >> c;
t = a * b + c;
sum = 0;
while (t != 0)
{
sum = sum + t % 10;
t = t / 10;
}
cout << sum << " ";
}
return 0;
}
Input:
2
123 456 789
321 654 987
Output:
33 15
I am using this New and improved code I corrected in order to solve this question I have.
I am using modular Exponentiation to use the formula [a^k mod n] to get my answer for an assignment I had to do where I was required to code it in two steps.
First int k must be converted to a binary
representation K consisting of a list of 0s and 1s. Second, Modular Exponentiation must be performed
using a, n and K[] as arguments..
Earlier My code was incorrect and was able to correct it.
The Problem I now face is that when I google the online calculator for modular Exponentiation of 5^3 % 13, it should == 8
The result that I get from my code is 5.
I am trying to understand if there something minor I'm missing from the code or my math is wrong? Thanks
#include <iostream>
#include <vector>
using namespace std;
vector <int> BinaryK(int k);
int ModularExpo(int a, vector <int> & k, int n);
int main()
{
int a = 0;
int k = 0;
int n = 0;
cout << "a^k % n" << endl;
cout << "a = ";
cin >> a;
cout << "k = ";
cin >> k;
cout << "n = ";
cin >> n;
vector<int> B = BinaryK(k);
int result = ModularExpo(a, B, n);
cout << "a ^ k mod n == " << result << endl;
return 0;
}
// c == b^e % m
vector<int> BinaryK(int k)
{
vector<int> K; //hint: make K a vector
int tmp = k;
while (tmp > 0)
{
K.push_back(tmp % 2); //hint: use pushback
tmp = tmp / 2;
}
return K;
}
int ModularExpo(int a, vector<int> & K, int n)
{
if (n == 1)
return 0;
int b = 1;
if (K.size() == 0)
return b;
int A = a;
if (K[0] == 1)
b = a;
for (int i = 1; i < K.size() - 1; i++)
{
A = A * A % n;
if (K[i] == 1)
b = A*b % n;
}
return (b);
}
Change this one line:
for (int i = 1; i < K.size(); i++) // K.size() not K.size()-1
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)
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)
I need to write a function head that returns the number of representations of a number as a sum of 3 positive squares.
For example, the only representation of 3 as a sum of 3 squares is 3 = 1+1+1, so the function should return 1 if number = 3. If n is 27, the function should return 2 since 27 has two representations 27 = 25 + 1 +1 or 9+9+9.
This is what I have tried:
#include <iostream>
#include <cmath>
using namespace std;
int numRep(int num);
int main()
{
int count = numRep(27);
cout << count;
return 0;
}
int numRep(int num)
{
int count = 0, sum = 0;
int a =1, b=1, c=1;
while(a*a <= num -2)
{
b = 1;
while(b*b <= num -2)
{
c =1;
while(c*c <= num -2)
{
sum = a*a + b*b + c*c;
if (sum == num) count++;
c++;
}
b++;
}
a++;
}
return count/3;
}
But I am not getting correct output. Need some guidance... If there is a better method, do suggest..
Here is a good starting point:
#include <cmath>
#include <iostream>
int count_sum_of_squares(int n)
{
int count=0;
// We only need to test numbers up to and including the square root of n.
// Also, we want to impose an ordering on [a, b, c] to consider
// combinations and NOT permutations.
for (int a=1; a<=int(sqrt(n)); ++a)
for (int b=1; b<=a; ++b)
for (int c=1; c<=b; ++c)
if (a*a+b*b+c*c==n) // If the squares of {a, b, c} add up to n
++count; // then this is a case that should be counted
return count;
}
int main()
{
std::cout << 3 << ': ' << count_sum_of_squares(3) << '\n';
std::cout << 14 << ': ' << count_sum_of_squares(14) << '\n';
std::cout << 27 << ': ' << count_sum_of_squares(27) << '\n';
std::cout << 866 << ': ' << count_sum_of_squares(866) << '\n';
}
Instead of searching from 1 to num - 2, you should only search from the current index loop above. That way, you don't repeat any terms.
#include <iostream>
#include <cmath>
using namespace std;
int numRep(int num);
int main()
{
int count = numRep(27);
cout << count << endl;
return 0;
}
int numRep(int num)
{
int count = 0, sum = 0;
int a =1, b=1, c=1;
while(a*a <= num -2)
{
b = a;
while(b*b <= num -2)
{
c =b;
while(c*c <= num -2)
{
sum = a*a + b*b + c*c;
if (sum == num) {
count++;
}
c++;
}
b++;
}
a++;
}
return count;
}
You're getting all the permutations, and you want all the combinations.
Example: numRep(14) will give you 6, when I think you want it to only have 1.
a = 1, b = 2, c = 3
a = 1, b = 3, c = 2
a = 2, b = 1, c = 3
a = 2, b = 3, c = 1
a = 3, b = 1, c = 2
a = 3, b = 2, c = 1
You'll need to keep track of your answers, preferably sorted with a-c going from lowest to highest, and don't increment your count if it already exists.
This works for me:
int numRep(int num){
int count = 0;
for(int a = 1; a * a <= num ; ++a)
for(int b = a; b * b <= num ; ++b)
for(int c = b; c * c <= num ; ++c)
if (a*a + b*b + c*c == num)
count++;
return count;
}
Only start with b from a, and with c from b so you won't count twice the same solution.
The complexity of this is O(N*sqrt(N)) I think.
Just start second loop from a. And you don't need a third loop at all. c = sqrt(num - a*a - b*b). If this calculated c is an integer, then it counts.