I'm having trouble with the following assignment, mostly because I don't understand how a Boolean function works. "Write a function called Divisible that takes in two numbers as parameters. Return True if the first number is
evenly divisible (no remainder) by the second number. Otherwise return False. Hint: Use %"
Currently what I have is:
int Divisible()
{
int firstNum;
int secondNum;
int result;
cout << "Please enter any integer: ";
cin >> firstNum;
cout << "Please enter another integer: ";
cin >> secondNum;
result == firstNum%secondNum;
}
I'm not sure what to do beyond that. I thought I could assign bool = 0 as true but that doesn't appear to be the case. I'm still very new to C++ so any help would be appreciated.
The question asks you to write a method that takes the numbers as parameters, not let's you input them from standard input.
Boolean is a type of its own in c++, so you want the method to return bool and not int.
An easy to read solution:
bool Divisible(int a, int b) {
int remainder = a % b; // Calculate the remainder of a and b.
if(remainder == 0) {
return true; //If the remainder is 0, the numbers are divisible.
} else {
return false; // Otherwise, they aren't.
}
}
Or more concise:
bool Divisible(int a, int b) {
return (a % b) == 0;
}
Even more concise:
bool Divisible(int a, int b) {
return !(a % b);
}
When creating functions or using them always remember to start with the signature.
Think what will this function need to work with, and what will it return. You need to return if something is true or false, which are values of data type bool. Just like in a conditional such an if statement you may use Boolean operators like ==, != and etc.
So you need to return a bool and check if two numbers are divisible. Therefore:
bool Divisible(int a, int b){
// == boolean operator that will return true if a%b evaluates to 0
// false if not
return (a % b) == 0
}
Once you start thinking of functions this way, every program becomes one great puzzle!
In methods that return boolean, you want to first determine what the value of the result will be when the method returns true, and then use the == operator to evaluate any result you get against the acceptable result.
So in your case, you are trying to determine whether to return true or false depending on if the first number is evenly divisible by the second.
First thing you do is you take a case that should work, ex:
4, 2
How do you know 4 is divisible by 2? Well this means that if I divide 4 by 2, then the remainder should be zero. This is what the % operator returns. If you do 4 % 2 the value is zero.
Ok so now you have the correct result so what you simply do now is to evaluate any result you get against the accepted result like so:
int isDivisible(int a, int b)
{
const int acceptedAnswer = 4 % 2;
if ( a % b == acceptedAnswer )
return 1;
return 0;
}
And there you have it, any value you get that does not equal your accepted answer will return 0 or not equal (!=) and any other answer will return 1 or equal (==)
You don't return; or assign a result...
result = firstNum%secondNum;
return (result == 0); // Assuming you want 0 as true.
In general, the value 0 is false and any value that is not (!0) is true. By convention, that is 1.
what you have done is correct but in last line you are comparing an uninitialized integer with result (remainder of division).
set int result=0;
and then do this:
return result==firstNum%secondNum; // checks if remainder is zero (true if zero)
you could also simply do return (firstNum%secondNum)==0
Furthermore, your assignment asks for a function that takes in two numbers as parameters (input arguments).
So your function prototype should be something like:
bool Divisible(int a, int b);
and you should use a and b in the function instead of taking input from stdin as you are doing right now.
bool is a type that can hold only two values: true and false. You use it for expressing truth values, as whether a number divides another or not.
In your case, the function could have been implemented as follows:
bool is_divisible(int a, int b)
{
return a % b == 0;
}
In the assignment there is clear written that the function must have two parameters. So the function could look the following way (C++)
inline bool Divisible( int n, int m ) { return ( n % m == 0 ); }
or (C)
inline _Bool Divisible( int n, int m ) { return ( n % m == 0 ); }
In the last case you may substitute return type _Bool for int. In the firt case that is when C++ is used it is better to use return type bool.
The request to enter two numbers shall be outside the function. The function only allows to determine whether one number is divisible by other number.
Related
// This is a function to check if the given array is sorted or not by recurssion
#include<iostream>
using namespace std;
bool sorted(int arr[],int n)
{
if(n==1)
{
return true;
}
I am cofused here when n will reach 1 then it will return true to "restArray" after that if array is not sorted then how will "restArray" become false?
bool restArray = sorted(arr+1, n-1);
return (arr[0]<=arr[1] && restArray);
}
int main()
{
int arr[]={1,6,3,4,5};
cout<<sorted(arr,5);
return 0;
}
As in every recursion there are two cases
First the trivial case if (n == 1): An array of size 1 (ie only a single element) is always sorted. Thus it returns true and stops the recursion
And if n is still greater than 1, you do the recursive call and check if the array without the first element is sorted (bool restArray = sorted(arr+1, n-1)), then you check if the first element of the array is less than the second element (a[0] < a[1]). (btw I'd probably check for <= here) And finally you combine those two checks with &&.
So for your example, it will at some point in time check 6 < 3, which will return false thus the overall result will become false.
But for sake of optimization, I'd suggest to reorder your statements a bit, such that you won't need the recursive call, if the order of the first two elements in the array is already wrong. And as #Scheff's Cat mentioned in the comments: When you convert it to a tail recursion, any decdent compiler will be able to refactor that recursion into a (much cheaper) iteration ...
And I'd also check for n <= 1 otherwise you might end up in an infinite recursion if you method is (wrongly!) called with n = 0.
bool sorted(int arr[],int n)
{
if (n <= 1)
{
return true;
}
return arr[0] <= arr[1] && sorted(arr+1, n-1);
}
or even simpler
bool sorted(int arr[], int n) {
return n <= 1
? true
: arr[0] <= arr[1] && sorted(arr+1, n-1);
}
Disclaimer: This question is more of a challenge, and the post is also quite long. Read only in free time!
The Problem:
Basically, suppose there is a single line of integer inputs:
32352\n // assuming single digits only and no spaces for simplification
We have to remove duplicates from the inputs, and then display them. So, output should be:
After removing duplicates: 2, 3, 5 // display them in any order
However, there is a catch:
Do not use any data structures containers.
Edit: I believe containers are what I meant (thanks Vlad!).
So, my question is: What is the error in my implementation, and is there another (better) way to do it?
My thought process:
Since we are not allowed use of any data structure, we cannot store the inputs (I think?).
However, since it is already stored in memory on input, that is not a problem.
More of a problem is removing the duplicates. We will have to manipulate the input stream.
The first thing that struck me is that we can sort the inputs. That is,
32352
becomes:
22335
And now, simply print the first element of each range.
Working on this idea, I came across the std::cin.get() and std::cin.putback() methods, both accepting a char.
I also realized I would have to use recursion.
And hence, the code becomes (I have used insertion sort):
The Code:
The sort() function is where the error is. It uses a running index ala arrays, and this is used to uniquely identify each element.
In each iteration, the index_of_element element is found and selected, and we determine where in the remaining (virtual) array, we need to place it. For example, if in our original input:
32352 // S = sorted subarray
SU--U // U = unsorted subarray
, the first 2 is selected, we "shift" 3 (as 3 < 2).
Now, there are no more elements left to shift, we "place" 2.
The result should become:
23352
SSU-U
The (buggy) implementation:
bool sort(int index_of_element, int index = 0, char prev_element = 0)
{
static char element;
char digit;
// retrieve an element from memory
std::cin.get(digit);
// If not end of input
if(digit != '\n')
{
// store the element for comparision
if(index == index_of_element)
{
element = digit;
}
// continue forward until '\n'
bool result = sort(index_of_element, index + 1, digit);
// if we are in sorted subarray
if(index <= index_of_element)
{
// If element belongs here(also if this is first element(prev_element is 0)), place it
if(element > prev_element)
{
digit = element;
// Signal that element has been placed
element = 0;
}
// Else, if element not already placed, we need to shift elements
else if(element != 0)
{
// Place the previous element here
digit = prev_element;
}
}
// Put it back in memory
std::cin.putback(digit);
// And return the result
return result;
}
// Which is generated here when end of input is reached
else
{
// If sorted all elements, break loop
if(index_of_element == index)
{
return false;
}
// Else, continue sorting
else
{
return true;
}
}
}
(A wall of code, but I didn't want to skip anything relevant), and it should be used as:
...
int index_of_element = 0;
while(sort(index_of_element++));
...
The display function is ready, and it works properly.
What I do know is that it gets stuck in an infinite loop and the values are lost.
What is going wrong?
And should I add the output (The post is already very long)?
The problem seems to be that you don't put the newline back into the stream, while your code assumes that it will be there.
That is, after your first pass, digit != '\n' is always true.
Put the newline back into the stream, or break when you've reached the true end-of-stream.
(There could also be problems with (ab)using std::cin like this, but I'm not sure, and that's another matter anyway.)
You can do it with only function objects, in a single pass.
#include <iostream>
#include <sstream>
#include <functional>
void print_unique_ints(std::istream & in, std::ostream & out, std::function<bool(int)> unseen) {
for (int i; in >> i;) {
if (unseen(i)) {
out << i << ' ';
print_unique_ints(in, out, [&](int j){ return (i != j) && unseen(j); });
return; // not actually needed, previous call only ends when input is exhausted
}
}
}
int main() {
print_unique_ints(std::cin, std::cout, [](int){ return true; });
}
See it live
Each call to print_unique_ints skips previously seen ints, prints the unseen int, and adds to the filter
Substituting values for variables; and function calls for expressions; in the first call
for (int i; in >> i;) { // i = 3
if (true) {
out << 3 << ' ';
print_unique_ints(...) // see below
}
}
The second
for (int i; in >> i;) { // i = 2
if ((3 != i) && true) {
out << 2 << ' ';
print_unique_ints(...) // see below
}
}
The third
for (int i; in >> i;) { // i = 3, 5
if ((2 != i) && (3 != i) && true) { // skips over the 3
out << 5 << ' ';
print_unique_ints(...) // see below
}
}
The forth
for (int i; in >> i;) { // i = 2
if ((5 != i) && (2 != i) && (3 != i) && true) { // skips the 2 and finds the end of input
}
}
Note that && true never changes the result in the if
A variation of bitset (or mask) implem...using the commutative property of multiplication
Take a function f which maps every digit to a unique prime p_i
0 1 2 3 4 5 6 7 8 9
2,3,5,7,9,11,13,17,19,23
If all numbers are found the total amount to N=2*3*5*7*9*11*13*17*19*23=2007835830
Consume cin as c, if f(c) divides N, print c and update N /= f(c)
#include <iostream>
#include <sstream>
int f(char c){
if(c=='0') return 2;
if(c=='1') return 3;
if(c=='2') return 5;
if(c=='3') return 7;
if(c=='4') return 9;
if(c=='5') return 11;
if(c=='6') return 13;
if(c=='7') return 17;
if(c=='8') return 19;
if(c=='9') return 23;
}
int main() {
std::istringstream in("2 2 2 3 5");
int N = 2007835830;
char c;
while(in >> c){
if(c=='\n') break;
int p_i = f(c);
if(N % p_i == 0){
N = N/p_i;
std::cout<<c<<" ";
}
}
}
I am sure that this phrase
Remove duplicates from input without use of any data structures
means that you shall not use any container like for example std::string or an ordinary array.
The assignment is not simple for a beginner.
Here are my five cents.
#include <iostream>
#include <type_traits>
template <typename T>
T remove_duplicates( T n )
{
static_assert ( std::is_integral<T>::value );
const T Base = 10;
T result = n % Base;
for ( T multiplier = 1; n /= Base; )
{
T digit = n % Base;
T tmp = result;
bool unique = true;
while ( ( unique = tmp % Base != digit ) && ( tmp /= Base ) );
if ( unique )
{
multiplier *= Base;
result = digit == 0 ? result * multiplier + digit
: digit * multiplier + result;
}
}
return result;
}
int main()
{
for ( int n : { 0, 1, 10, 101, 100, 10203, -1, -10, -101, -100, - 10203 } )
{
std::cout << n << ": " << remove_duplicates( n ) << '\n';
}
return 0;
}
The program output is
0: 0
1: 1
10: 10
101: 10
100: 10
10203: 1230
-1: -1
-10: -10
-101: -10
-100: -10
-10203: -1230
That is you are building a new number from the source number by checking whether the new number already contains a digit from the source number.
The function can work with any integer type signed or unsigned. It correctly processes digits equal to 0.
It was said not to use any arrays, vectors, stacks, queues etc and neither our own implementations of it. I simplified the condition.
Well I've got bad news for you; this is not possible.
Given an input of length N you will need to somehow remember the previous N - 1 values to decide whether to print the Nth value or not. This is not possible with constant space.
So you need some data structure.
Now ...
Since we are not allowed use of any data structure, we cannot store the inputs (I think?).
However, since it is already stored in memory on input, that is not a problem.
So let's assume the existence of a (mutable) array of length N, containing the input values. Now we can solve this without using additional storage / data structures:
Select some value as special value
Iterate over the numbers until you find a value which is not that special value. print that value. Write the special value to the array where you found the value you just printed. finish iterating over the numbers, overwritte each occurrence of the just printed value with the special value.
repeat (from 2) until the input consists only of special values.
You just need to think about a way to handle the case where the special value was present in the input from the start.
I am doing an exercise where I need to find a positive integers p and q which are factors of another natural number n.
Following the formula n=pq*q where p is a squarefree number.
However, for some instances of the program my compiler detects a memory error saying that I am accessing an uninitialized value.
The logic I tried is as follows. Firstly, I took the number that needs to be factored (name it n). Next I found all factors of the number n and placed them in a vector. After that, check if every element of that vector is squarefree. If true, put the element in another vector(a vector of squarefree factors of the number n). After that, go through every element of the vector of squarefree factors and solve the equation q=sqrt(n/p) where p is the squarefree factor from the vector. Additionally, I check the condition if(int(sqrt(n/p))==sqrt(n/p)) because the square root needs to be a positive integer.
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
// Function that checks if the number is squarefree
bool isSquareFree(int n)
{
if (n % 2 == 0)
n = n / 2;
if (n % 2 == 0)
return false;
for (int i = 3; i <= sqrt(n); i += 2)
{
if (n % i == 0)
{
n = n / i;
if (n % i == 0)
return false;
}
}
return true;
}
void Factorise_the_number(int n, int &p, int &q)
{
if (n <= 0)
return 0;
vector<int> factors(0); // vector of factors
vector<int> sqfree_factors(0); // vector of squarefree factors
int sqfree_number; // the number "p"
int squared; // is essentially the number "q"
for (int i = 1; i <= n / 2; i++)
{
if (n % i == 0)
factors.push_back(i); // takes all factors of the number "n"
}
for (int i = 0; i < factors.size(); i++)
{
if (isSquareFree(factors.at(i)))
sqfree_factors.push_back(factors.at(i));
} // checks if each factor is squarefree. if yes, put it in a separate vector
for (auto x : sqfree_factors)
{
if (int(sqrt(n / x)) == sqrt(n / x))
{ // if true, we found the numbers
squared = sqrt(n / x);
sqfree_number = x;
break;
}
}
p = sqfree_number;
q = squared;
}
int main()
{
int n, p = 0, q = 0;
cin >> n;
Factorise_the_number(n, p, q);
cout << p << " " << q;
return 0;
}
For example, my program works if I enter the number 99, but doesn't work if I enter 39. Can anyone give any insight?
Thanks!
As you said, for 39 it doesn't work. Have you checked what it's doing with 39? You should do it, as it is the best way to debug your program.
Let's have a look at it together. First it tries to find all the factors, and it finds 1, 3 and 13: this looks fine.
Then, it checks whether each of those numbers is squarefree, and they all are: this also looks correct.
Then, it checks whether any of the squarefree factors satisfy the equality you are looking for. None of them does (39 is 3 x 13, there's no way it can contain a squared factor). This means that if (int(sqrt(n / x)) == sqrt(n / x)) is never true, and that block is never run. What's the value of sqfree_number and squared at that point? It is never initialised. Using uninitialised values leads to "undefined behaviour", that is, your program can do anything. In this case, p and q end up containing random values.
How can you fix it? Consider this: if n doesn't satisfy your equation, that is, it can't be expressed as pq*q, what, exactly, should the program output? Would your output, as it is now, ever make sense? No. This means you have to modify your program so that it covers a case you hadn't considered.
A way is to add a bool found = false; just before your final for loop. When you find the factors, before breaking, set that variable to true. Then, outside the loop, check it: is it true? Then you can return the correct values. But if it's still false, it means the equality doesn't hold, and you can't return correct values. You have to find a way to signal this to the caller (which is your main function), so that it can print an appropriate message.
And how can you signal it? In general, you could change your Factorise_the_number (by the way, the name of functions should start with a lowercase letter; uppercase letters are usually used for classes) to return a bool. Or you could use a trick: return a special value for p and q that cannot be the result of the calculation. Like -1. Then, before printing, check: if the values are -1, it means the number can't be expressed as pq*q.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I just came upon one problem. I wanted to compare whether my Eratostenes's Sieve contains prime numbers or not. In the code i have this line
if (sieve[2] == is_prime(2)) // returns false
printf ("true");
Now, sieve[2] is a boolean and it's value is true (I even checked in the array, so there's no doubt about it). is_prime(2) is a boolean aswell (I also checked).
Now my problem. The line presented above returns false. Yes - it returns false even though it's statement is:
if ( true == true ) // which normally returns true
printf ("true");
However, after removing one equation sign:
if ( sieve[2] = is_prime(2) ) // returns true
printf ("true");
This statement returns true.
Can someone briefly explain how does one equation mark work in this case in comparison to ==?
Thanks in advance
EDIT
is_prime:
bool is_prime(int x) {
unsigned int i,j,k;
if (x < 2) return false;
else {
for (i=2; i!=x; i++) {
if (x == i) return true;
else if (x % i == 0) return false;
}
}
}
sieve:
const int n = 10000;
bool sieve[n+1];
.
.
unsigned long int i;
sieve[0] = sieve[1] = false;
for (i=2; i<=n; i++) sieve[i] = true;
for (i=2; i*i<=n; i++) {
if (sieve[i]) {
unsigned tmp = 2*i;
while (tmp <= n) {
sieve[tmp] = false;
tmp += i;
}
}
}
[EDIT2]
The problem was with "is_prime(x)" Changed loop condition from "i!=x" to "i<=x"
Sorry for the trouble and thanks for the answers
UPDATE
bool is_prime(int x) {
unsigned int i,j,k;
if (x < 2) return false;
else {
for (i=2; i!=x; i++) {
if (x == i) return true;
else if (x % i == 0) return false;
}
}
}
Your is_prime() (above) is broken, with undefined behaviour, as when x is 2 (or indeed any actually prime number) it reaches the end of the function without having a return statement - the i!=x test means the x == i inside the loop can never be true.
is_prime(2) it's likely to return effectively random results (based on left over stack or register content / in your documented output it's seeming "returning" x itself, presumably because your ABI uses the same CPU register or stack address to pass in the argument and pass back the function's return value).
Specifically for 2, flow enters the first else clause, then with i=2 the first i!=x test fails and the for loop immediately exits... there's no return after the for's scope. Minimally corrected code (faster implementations are possible, but keeping the simplicity and intended logic):
bool is_prime(int x)
{
if (x < 2) return false;
for (int i = 2; i < x; ++i)
if (x % i == 0)
return false;
return true;
}
Equivality / ==
With sieve[2] == is_prime(2) it's checking they have the same value - possibly after converting one of the values to enable the comparison, but you say they're both booleans so that's not necessary. This would yield a "true" value for the if when they're both true or both false.
Now my problem. The line presented above returns false. Yes - it returns false even though...
That doesn't make any sense... I suggest you add the following before the if statement to check the variables' values:
std::cout << "sieve[2] " << sieve[2] << " (bool)" << (bool)sieve[2]
<< ", is_prime(2) " << is_prime(2) << std::endl;
I even checked in the array, so there's no doubt about it
Be wary of mistakes like seeing the array content displayed ala { true false true false } and thinking [2] is the second value... it's actually the third. as array indexing starts at 0.
Assignment / =
With sieve[2] = is_prime(2) you're assigning the value of is_prime(2) into sieve[2], and the if statement is deemed "true" if that value is deemed true in a boolean context (i.e. it's a boolean with value true, or a non-0 number or pointer etc.). For most data types, the execution flow of if (sieve[2] = is_prime(2)) ... is the same as simply if (is_prime(2)) ..., but of course it also modifies sieve[2].
It assigns the right hand operand to left, and returns the left operand.Since you are assigning true to your variable, it evaluates to true. If you set your variable to false, you don't get the output, e.g:
bool x;
if(x = false)
printf("this won't be printed");
Here the equal affect the left operator with the value of the right operator then test the value. So the result must be the value of the right operator.
Your loop in is_prime will never run for the check x == i will be true, because it runs as long as x != i. Those two conditions are mutually exclusive.
That means the function will end without a return statement, which leads to undefined behavior.
This
if ( sieve[2] = is_prime(2) )
contains an assignment, not a comparison.
As the value of an assignment is the value assigned, it is true whenever is_prime(2) is.
However, let's look at your is_prime and see what happens if we pass it a 2...
bool is_prime(int x) {
unsigned int i,j,k;
So far, so good, but j and k are never used, so they shouldn't really be here.
if (x < 2) return false;
2 isn't less than 2, so we'll continue...
else {
for (i=2; i!=x; i++) {
OK, set i = 2, and compare it to x which is 2, and... oops, i is equal to x, so we'll abandon the loop immediately...
if (x == i) return true;
else if (x % i == 0) return false;
}
}
... and fall through here, where we're not returning a value like we promised, and causing undefined behaviour.
}
So, your program is undefined (you really should switch on compiler warnings, or start listening to them).
And this happens on every number that is prime.
You can rewrite the loop like this:
for (i=2; i <= x; i++) {
if (x == i) return true;
else if (x % i == 0) return false;
}
or
for (i=2; i < x; i++) {
if (x % i == 0) return false;
}
return true;
Why does if (is_prime(2)) appear to work?
(Since this code is undefined, the following is largely speculation and should only be taken with suitable measures of salt.)
Often, when a function is supposed to return something but doesn't, the calling function will just grab whatever is stored in the place where the return value should have been and use that.
This value is in this case very likely not the same as the bit pattern that represents true, so will compare unequal to true, in if (is_prime(2) == true).
It will however, also very likely, not be the bit pattern that represents false either, so will be considered true in a conditional, if(is_prime(2)).
I am new to C++ development and I was hoping someone could help me with something I have been trying to do.
Say for example I want a function that will, given an integer input, return the number of distinct digits it contains.
So for example, if I have three integers:
int a = 19876;
int b = 25644;
int c = 4444;
If I pass 'a' into the function, I would expect the number 5 to be returned.
If 'b' was passed into the function, I would expect '4' to be returned,
If 'c' was passed into the function, then 1 would be returned, as they are the number of distinct numbers.
Could someone please illustrate how I could achieve this?
You mean you want to find the number of different decimal digit in the integer?
int distinct_digits(int value) {
std::ostringstream out;
out << value;
std::string digits = out.str();
std::sort(digits.begin(), digits.end());
return std::unique(digits.begin(), digits.end()) - digits.begin();
}
(not compiled or tested but the basic idea should work)
Using the mod operator and you can count it:
int distinct(int a)
{
int ele[10]={0};
if(a==0) return 1;
if(a<0) a=a*-1;
while(a)
{
int t=a%10;
ele[t]=1;
a=a/10;
}
for (i=0;i<10;i++)
if (ele[i])
count++;
return count;
}
This will work only for both positive numbers and negative numbers.
This could be more concise, but I'm helping you see the way the solution works.
int digitCount(int number) {
// make an array to store whether you've seen a given digit
// note that there are 10 elements, one for each digit
// this will be conveniently indexed 0-9
bool digitSeen[10];
// set each seen digit
int count = 0;
while (number != 0) {
// get the rightmost digit with the modulo operator (%)
int digit = number % 10;
if (digitSeen[digit] == false) {
// only count if this is the first time we have seen it
++count;
digitSeen[digit] = true;
}
// pop off the right-most digit by dividing by 10
number /= 10;
}
return count;
}
You can compute the distinct number thing just fine, but there's no way to go from 'a' to the value of the variable a;. You can hardcode it- but that's fairly maintenance-heavy.
if you mean to return a floating point to get a decimal just return it as a float and the compiler should to an implicit type conversion. this is not generally good code but it works. a better way might be to hand the value to a temporary float like
float a_float = a;
return a_float;