I need to see if two numbers are multiples - c++

I need to see if two numbers are multiples, and in case they are provide a positive answer, or in case they are't provide a negative one. However, everytime i try to make the prog there are always errors, i'm not sure i'm doing it right.
int A;
int B;
float C;
printf("enter two numbers\n\n");
scanf("%d %d", &A, &B);
C=A/B;
D=A/B;
if (A/B=C) printf ("no");
else printf ("yes");

An obvious error in your code is
if (A/B=C)
// ^ you are using assignment (=) here, not comparison (==)
try
if (A/B==C)

With A,B > 0; A and B are multiple if A % B == 0 or B % A == 0
(% is the modulo operator)
so
bool isMultiple(unsigned int A, unsigned int B)
{
if (A == 0 || B == 0) {
return A == B;
}
// A != 0 && B != 0
return (A % B == 0) || (B % A == 0);
}

Related

What will be the difference between this two codes

Why my second code is not giving expected result. I know using parenthesis it will work fine but why it is not giving correct answer without parenthesis. Can anyone please explain the logic behind this?
Here I used parenthesis and it gives correct answer, 4.
// returns 4
int bitDiff () {
int a=10, b=20;
int count=0;
while(a || b) {
if ((a&1) != (b&1))
count++;
a=a>>1;
b=b>>1;
}
return count;
}
Here I have not used parenthesis, so it is giving me wrong ans, 2.
// returns 2
int bitDiff () {
int a=10, b=20;
int count=0;
while(a || b) {
if (a&1 != b&1)
count++;
a=a>>1;
b=b>>1;
}
return count;
}
refer to C++ Operator Precedence , as it states that :
10: == and != For equality operators = and ≠ respectively
11: a&b Bitwise AND
where 10 represents a higher Precedence over the 11
so in the second example : != will be evaluated first from left right then the & will be evaluated next.
so in the second example, in the first iteration : (a&1 != b&1) is equivalent to
a&(1 != b)&1
10&(1 != 20)&1
10&1&1 = 0
while in the first example, in the first iteration : ((a&1) != (b&1)) is equivalent to
(a&1) != (b&1)
(10&1) != (20&1)
0 != 0 which is equivalent to 0
as the operator () has a higher precedence over !=

GCD of Multiple Number

I know how to write a code finding a GCD of 2 number . However, I am trying to solve a problem of finding a GCD of n number and I think the algorithm is a little bit different than using an Eucledian algorithm. My code can be compiled , but it always gave me the wrong result. For example when i put n = 2 , GCD of 16 and 12 it gave the answer 8. Here is my code :
#include<iostream>
using namespace std;
int main()
{
int a,b[100],c,d,e=0;
cin>>a;
for(c=0 ; c<a ; c++)
{
cin>>b[c];
}
for(c=0 ; c<a-1 ; c++)
{
if(c < 1)
{
d = b[c];
}
if(b[c] < d)
{
d = b[c];
}
}
while(d>0)
{
for(c=0 ; c<a ; c++)
{
if(b[c] % d < 1)
{
e++;
}
}
if(e == c)
{
cout<<d;
break;
}
d--;
}
}
Can you guys please find the mistake in my code?
Your code does not compute the greatest common divisor of the input array - it counts how many of the entries are evenly divisible by the smallest element d of the array, then how many are divisible by one smaller, and so on until d is 0. This has nothing to do with the GCD at all.
One easy way - though not necessarily the fastest - would be based on the fact that the GCD of three numbers must be the same as the GCD of any one of those numbers and the GCD of the other two.
gcd(a, b, c) = gcd(gcd(a, b), c) = gcd(a, gcd(b, c)) = gcd(gcd(a, c), b)
Extension to n inputs is elementary:
int result = a[0];
for (int i = 1; i < a.Length; ++i)
result = gcd(result, a[i]);
Code for the GCD of two numbers can be found all over the 'net, for example at Rosetta Code. One of my favourites is this plain iterative version:
int gcd (int a, int b)
{
while (b)
{
int t = b;
b = a % b;
a = t;
}
return a;
}
C# allows a more succinct formulation but in other languages this probably won't work (in C++ it would invoke undefined behaviour, for example):
static int gcd (int a, int b)
{
while (b != 0)
b = a % (a = b);
return a;
}
In case some find it helpful, here is an implementation of the Euclidean algorithm in JavaScript.
function EuclideanGCD(a, b) {
// Make sure a > b, interchange values
if (a < b) {
c = a;
a = b;
b = c
}
// If A = 0 then GCD(A,B) = B and we can stop.
if (a == 0) {
return b;
// If B = 0 then GCD(A,B) = A and we can stop.
} else if (b == 0) {
return a;
} else {
let gdc = 0;
let quotient = Math.floor(a / b); // Get the divisor
let remainder = a % b; // Get the remainder
// Make a recursive call, till we hit 0
gdc = EuclideanGCD(b, remainder);
return gdc;
}
}
var gcd = EuclideanGCD(234, 357);
console.log(gcd); // Outputs: 3

warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]

I was solving a problem. The question goes like this: Jill & Jung love lucky numbers. The lucky numbers is obviously 4 & 7, if a decimal representation of positive numbers contains 4 & 7, the positive integer is considered lucky. For example 444, 474 and 7 are lucky, where 4773 and 89 are not lucky.
Jill wanted to convert non-lucky integers to lucky integers, by discarding the non-lucky digits in an integer. For Example answer for number 767456 is 774, answer for number 9974 is 74, answer for 1775667 is 777.
Jill will give you two numbers a and a lucky number b. Find an minimum positive integer c (c > a) that will contain a lucky integer 'b'.
Input Format:
Integer t: number of test cases. Follow two integers a and b (1 <= a, b <= 100000). b is always a lucky Integer.
Output Format:
print a minimum number c that contains the lucky number b
Sample Input
1
47 74
Sample Output
74
I am just a beginner in C. I wrote the following code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int r1, r2, c1, c2, d1, d2, a, b, c, d, n, x, i, flag = 0;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d%d%d%d%d%d", &r1, &r2, &c1, &c2, &d1, &d2);
for (a = 0; a < 25; a++)
for (b = 0; b < 25; b++)
for (c = 0; c < 25; c++)
for (d = 0; d < 25; d++) {
if ((a + b == r1) && (c + d == r2) &&
(a + c == c1) && (b + d == c2) &&
(a + d == d1) && (c + b == d2) &&
a > 0 && b > 0 && c > 0 && d > 0) {
printf("YES\n");
break;
} else
flag = 1;
}
if (flag == 1)
printf("NO\n");
}
return 0;
}
I got the following error. Please help me.
solution.cc: In function 'int main()':
solution.cc:10:19: warning: ignoring return value of 'int scanf(const char*, ...)',
declared with attribute warn_unused_result [-Wunused-result]
scanf("%d",&n);
^
solution.cc:13:25: warning: ignoring return value of 'int scanf(const char*, ...)',
declared with attribute warn_unused_result [-Wunused-result]
scanf("%d%d",&a,&b);
^
If you do not enter numbers when scanf expects them, it will return a number of successful conversions less then what you expect. It is not a syntax error to ignore this return value, but it is very sloppy as your program will behave in undefined ways if not enough numbers are input.
Fix the code this way:
if (scanf("%d", &n) != 1) {
printf("expected number\n");
return 1;
}
for (i = 0; i < n; i++) {
if (scanf("%d%d%d%d%d%d", &r1, &r2, &c1, &c2, &d1, &d2) != 6) {
printf("missing numbers\n");
return 1;
}
...
Furthermore, the rest of the code does not seem to have any connection to the lucky number problem.

Is there a more elegant syntax for these boolean expressions?

I was just writing an improved linear version of a recursive Fibonacci algorithm, and realized that my boolean expressions look really bad and unreadable. Is there a cleaner way to do what I'm trying to do?
int fibonacci(int num) {
if (num <= 1)
return num;
// starts looking ugly here
int a = intExists(num-1);
int b = intExists(num-2);
bool aAndB = (a != -1 && b != -1);
bool justA = (a != -1 && b == -1);
bool justB = (a == -1 && b != -1);
int number = 0;
if (aAndB)
number = (a + b);
else if (justA)
number = (a + fibonacci(num - 2));
else if (justB)
number = (fibonacci(num-1) + b);
else
number = (fibonacci(num - 1) + fibonacci(num - 2));
map.push_back(Pair(num, number));
return number;
}
Thanks
If you're talking about:
bool aAndB = (a != -1 && b != -1);
then I would say, "no."
This code looks perfectly expressive to me. aAndB is initialized at the moment it comes in to being, and the conditions are very clear. This might look a bit odd when you're first starting out in C++, but before you know it it will be second nature and other constructs will seem silly.
One thing I would suggest is to make aAndB const if you don't intend to change it:
const bool aAndB = (a != -1 && b != -1);
This is even more expressive.
It also might give the compiler an additional opportunity to optimize your code.
Remember -- write code for humans to understand. Not for computers to understand.
Why don't you make a and b as bools and assign those as true if a == -1 and false otherwise. Then, the expressions will become easier to handle.
Could do a switch statement to clean up the if else statements a little. Other than that just add comments
You could rewrite it to use conditional branching, like this:
int fibonacci(int num) {
if (num <= 1)
return num;
int a = intExists(num-1);
int b = intExists(num-2);
const bool isA = (a != -1); // change in the definition
const bool isB = (b != -1); // change in the definition
int number = 0;
if (isA && isB)
number = (a + b);
else if (isA) // conditionnal branching
number = (a + fibonacci(num - 2));
else if (isB) // conditionnal branching
number = (fibonacci(num-1) + b);
else
number = (fibonacci(num - 1) + fibonacci(num - 2));
map.push_back(Pair(num, number));
return number;
}
I'm assuming that intExists(n) looks up map and if finds n in there, returns fibonacci(n) else it returns -1. Then you could do this:
int fibonacci(int num) {
if (num <= 1)
return num;
int a = intExists(num-1);
int b = intExists(num-2);
if (a == -1) // if a wasn't found, then compute it
a = fibonacci(num-1);
if (b == -1) // if b wasn't found, then compute it
b = fibonacci(num-2);
int number = a + b;
map.push_back(std::make_pair(num, number));
return number;
}
Bonus:
Here is another completely different implementation of fibonnacci() based on Binet's formula:
#include <cmath>
int fibonacci(int n) {
static const double e1 = 1.6180339887498948482045868343656; // = (1 + sqrt(5)) / 2
static const double e2 = -0.61803398874989484820458683436564; // = (1 - sqrt(5)) / 2
static const double c = 0.44721359549995793928183473374626; // = 1 / sqrt(5);
double f = c * (std::pow(e1, n) - std::pow(e2, n));
return static_cast<int>(f + 0.5);
}
int main() {
for (int n = 1; n < 15; ++n)
std::cout << fibonacci(n) << ' ';
}
It outputs:
1 1 2 3 5 8 13 21 34 55 89 144 233 377
Plain C++ code is clean enough:
bool a = intExists(num-1);
bool b = intExists(num-2);
if (a && b) {
//
} else if (a) {
//
} else if (b) {
//
} else {
//
}
int a = intExists(num-1);
int b = intExists(num-2);
bool aAndB = (a != -1 && b != -1);
bool justA = (a != -1 && b == -1);
bool justB = (a == -1 && b != -1);
Quick look into the approach you took. Under what circumstances can justB be true? (Hint: never)
That should help you simplify your approach, although there are better approaches than memoization.
Changing intExists to return boolean values, you can do a switch-case statements like that:
bool a = intExists(num-1);
bool b = intExists(num-2);
switch ((a << 1) + b) {
default: // none exists
case 1: // only b exist
case 2: // only a exist
case 3: // both exists
}
The rationale is to transform those booleans in a binary number
A slightly drastic rewrite is to let an external function handle the lookup table.
That way you don't need to care about more than one value at a time.
This one uses map so I didn't have to write so much in order to test it, but it should be easy enough to adapt:
std::map<int, int> table;
int fibonacci(int num);
int value(int num)
{
int result = table[num];
if (!result)
{
result = fibonacci(num);
table[num] = result;
}
return result;
}
int fibonacci(int num)
{
if (num <= 2)
return 1;
return value(num - 1) + value(num - 2);
}

Char swap in a file C++

I dont know why this will not work, i need to swap the two chars enterd as a and b, it compiles but all the chars are replaced with the char inputted as b, any advise?
while (n != exist)
{
cout<<"What is the letter you want to swap?"<<endl;
cin>>a;
cout<<"What is the letter you want to swap it with?"<<endl;
cin>>b;
if (inFile.is_open())
{
while (inFile.good())
{
inFile.get(c);
if( c = a )
{
outFile<< b;
}
else if (c = b)
{
outFile<< a;
}
else
{
outFile<< c;
}
}
}
else
{
cout<<"Please run the decrypt."<<endl;
}
cout<<"Another letter? <n> to stop swapping"<<endl;
cin>>n;
}
In if and else if you need to use == instead of =. In C++/C you use == for comparison and = for assignment.
if( c == a )
{
outFile<< b;
}
else if (c == b)
{
outFile<< a;
}
= is for assignment, use == for comparison.
The way you have it, as long as a is not 0(the integer 0, not the character '0'), that first branch will always be executed.
if( c = a ) and else if (c = b) are suspect. You are assigning the value of a to c and the value of b to c, respectively. I believe if the assignment operation completes successfully (which is it), the block will execute. I believe you want the == operator, instead of the = operator.
You are assigning values instead of testing.
It should be
if (c == b)
and
if (c == a)