I am not sure what the issue may be. I added "cout << count;" to the if statements to see why there is no return value 'val'.
But now I see there is an infinite loop occurring.
I'm essentially trying to count how many loops it takes for num = 0.
At first I thought it was num = count being in the loop.
Any suggestions? Thanks in advance.
#include <iostream>
using namespace std;
// hailstone function prototype
int hailstone(int &num);
int main()
{
int val;
cout << "Enter integer" << endl;
cin >> val;
hailstone(val);
cout << val << endl;
return 0;
}
// Pass values by reference to hailstone function header
int hailstone(int &num)
{
do
{
int count = 0;
// If num is even
// Divide by two
if(num % 2 == 0)
{
num = (num / 2);
count++;
cout << count;
}
// If num is odd
// Multiply by 3 and add 1
else if(num % 2 != 0)
{
num = (num * 3) + 1;
count++;
cout << count;
}
// Assign the number of steps to num
num = count;
} while(num > 0);
// Return the number of steps
return num;
}
There are a few issues here, but the most pertinent is this line:
// Assign the number of steps to num
num = count;
You're essentially resetting num after you update it based on the rules of the hailstone sequence. Because 'count' is initialized at the start of each loop and then iterated once in either the 'if' or 'else if' block, it is always one. Therefore, at the end of each loop, num is always 1.
Whether you are doing num = num/2; (for even numbers) or num = (num * 3) + 1 (for odd numbers), the number will never become 0 or less. That's why your code runs for infinite time. So you need to change the line while (num > 0); to while(num > 1); inside the function hailstone (maybe it is line number 54). As like as follow:
Old code:
int hailstone(int &num)
{
do
{
int count = 0;
// If num is even
// Divide by two
if(num % 2 == 0)
{
num = (num / 2);
count++;
cout << count;
}
// If num is odd
// Multiply by 3 and add 1
else if(num % 2 != 0)
{
num = (num * 3) + 1;
count++;
cout << count;
}
// Assign the number of steps to num
num = count;
} while(num > 0); //You need to change this line
// Return the number of steps
return num;
}
New Code:
int hailstone(int &num)
{
do
{
int count = 0;
// If num is even
// Divide by two
if(num % 2 == 0)
{
num = (num / 2);
count++;
cout << count;
}
// If num is odd
// Multiply by 3 and add 1
else if(num % 2 != 0)
{
num = (num * 3) + 1;
count++;
cout << count;
}
// Assign the number of steps to num
num = count;
} while(num > 1); //Here is the change
// Return the number of steps
return num;
}
Another issue: You declares num = count (in line 52), which will not return the actual value (if your code is for counting number of loops). Example: If the input is 12 than the loop will run for 10 times but your code will print 11, I don't think this line is required. Return the value of count variable after your do-while loop breaks.
Thanks
clearly either 'if' or 'else if' condition is going to be satisfied that will increment count to 1 , and assigning num =count makes num =1 ,so(num>0) is always true.so loop continues forever
do
{
int count = 0;
if (num % 2 == 0)
{
num = (num / 2);
count++;
cout << count;
}
else if(num % 2 != 0)
{
num = (num * 3) + 1;
count++;
cout << count;
}
num = count;
} while (num > 0);
Related
#include <iostream>
using namespace std;
int main() {
int n;
int reversedNumber = 0;
int remainder;
cout << "Enter an integer: ";
cin >> n;
while (n != 0) {
remainder = n % 10;
reversedNumber = (reversedNumber * 10) + remainder;
n /= 10;
}
if (reversedNumber == n)
cout << "YES";
else
cout << "NO";
return 0;
}
Hello, I want the compiler to show yes but when i enter 2356532 in my input shows No ,This program should show that the input is equal to the inverse number.`
You divide n /= 10 in your loop until you have 0 left so if (reversedNumber == n) will never be true for anything but 0 as input.
Save n before the loop and compare with the value you've saved after the loop.
Example:
int saved = n;
while (n != 0) {
remainder = n % 10;
reversedNumber = (reversedNumber * 10) + remainder;
n /= 10;
}
if (reversedNumber == saved) ...
Demo
You are clearly updating the value of n inside the while loop. At the end, its value will always be 0. Hence, your if statement will always return false.
I suggest you save the initial value of n in a new variable after getting user input and make the comparison between the reversedNumber and that value.
The part i am not able to solve is - i am checking the number digits weather they are other than 1 or 0 using the checknumber(). Now, if the digits are other than 0 or 1 then ask the user to enter the num again till the digits are 0 and 1 only. After this, convert into binary and then again check the number is greater than -1 and the number is in negative then only exit. the main function:
int main()
{
int num = 0, flag;
while (num > -1) {
do {
cout << "Enter Number: ";
cin >> num;
} while (checknumber(num, flag) == 0);
cout << "Result in Decimal = ";
cout << binaryToDecimal(num) << endl;
}
}
This is my checknumber():
int checknumber(int number, int flag)
{
while (number != 0) {
int val = number % 10;
if ((val != 1) && (val != 0)) {
flag = 0;
break;
}
else {
flag = 1;
}
return flag;
}
}
the output i am getting when entering the number other than 0 or 1:
In your checknumber function, you're never dividing number, and thus you're stuck in an infinite loop. You're also returning on the first iteration of the loop. I do not understand the usage of flag either.
A corrected checknumber would be:
int checknumber(int number)
{
while(number != 0)
{
int val = number % 10;
if((val != 1) && (val != 0))
{
return 0;
}
number /= 10;
}
return 1;
}
I have an assignment to make a program that should convert a number from it's integer value to a binary value. For some reason my array is always filled with zeroes and won't add "1"'s from my if statements. I know there are probably solutions to this assignment on internet but I would like to understand what is problem with my code. Any help is appreciated.
Here is what I tried:
#include <iostream>
/*Write a code that will enable input of one real number in order to write out it's binary equivalent.*/
int main() {
int number;
int binaryNumber[32] = { 0 };
std::cout << "Enter your number: ";
std::cin >> number;
while (number > 0) {
int i = 0;
if ((number / 10) % 2 == 0) {
binaryNumber[i] = 0;
}
if ((number / 10) % 2 != 0) {
binaryNumber[i] = 1;
}
number = number / 10;
i++;
}
for (int i = 31; i >= 0; i--) {
std::cout << binaryNumber[i];
}
return 0;
}
You need to remove number/10 in both the if statements. Instead, just use number. you need the last digit every time to get the ith bit.
Moreover, you need to just half the number in every iteration rather than doing it /10.
// Updated Code
int main() {
int number;
int binaryNumber[32] = { 0 };
std::cout << "Enter your number: ";
std::cin >> number;
int i = 0;
while (number > 0) {
if (number % 2 == 0) {
binaryNumber[i] = 0;
}
if (number % 2 != 0) {
binaryNumber[i] = 1;
}
number = number / 2;
i++;
}
for (int i = 31; i >= 0; i--) {
std::cout << binaryNumber[i];
}
return 0;
}
The first thing is the variable 'i' in the while loop. Consider it more precisely: every time you iterate over it, 'i' is recreated again and assigned the value of zero. It's the basics of the language itself.
The most relevant mistake is logic of your program. Each iteration we must take the remainder of division by 2, and then divide our number by 2.
The correct code is:
#include <iostream>
int main()
{
int x = 8;
bool repr[32]{};
int p = 0;
while(x)
{
repr[p] = x % 2;
++p;
x /= 2;
}
for(int i = 31; i >= 0; --i)
std::cout << repr[i];
return 0;
}
... is always filled with zeroes ... I would like to understand what is problem with my code
int i = 0; must be before the while, having it inside you only set the index 0 of the array in your loop because i always values 0.
But there are several other problems in your code :
using int binaryNumber[32] you suppose your int are on 32bits. Do not use 32 but sizeof(int)*CHAR_BIT, and the same for your last loop in case you want to also write 0 on the left of the first 1
you look at the value of (number / 10) % 2, you must look at the value of number % 2
it is useless to do the test then its reverse, just use else, or better remove the two ifs and just do binaryNumber[i] = number & 1;
number = number / 10; is the right way when you want to produce the value in decimal, in binary you have to divide by 2
in for (int i = 31; i >= 0; i--) { except for numbers needing 32 bits you will write useless 0 on the left, why not using the value of i from the while ?
There are some logical errors in your code.
You have taken (number/10) % 2, instead, you have to take (number %2 ) as you want the remainder.
Instead of taking i = 31, you should use this logic so you can print the following binary in reverse order:
for (int j = i - 1; j >= 0; j--)
{
cout << BinaryNumb[j];
}
Here is the code to convert an integer to its binary equivalent:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// function to convert integer to binary
void DecBinary(int n)
{
// Array to store binary number
int BinaryNumb[32];
int i = 0;
while (n > 0)
{
// Storing remainder in array
BinaryNumb[i] = n % 2;
n = n / 2;
i++;
}
// Printing array in reverse order
for (int j = i - 1; j >= 0; j--)
{
cout << BinaryNumb[j];
}
}
// Main Program
int main()
{
int testcase;
//Loop is optional
for(int i = 0; i < testcase; i++)
{
cin >> n;
DecToBinary(n);
}
return 0;
}
I am trying to find a reversed number and check that it is a palindrome or not from a different approach but I was getting a right reversed number up to two digits and if the digits are more than two then I am getting wrong output. I cannot understand why is this so as I think my code is right.
below is the code
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int num, rem, t, add;
cin >> t;
while (t--) {
int total = 0, count = 0, i = 1, quo = 0;
cin >> num;
quo = num;
while (quo > 9) //count determiner
{
quo = quo / 10;
++count;
}
while (count >= 0) //reverse number saved in total
{
int den = pow(10, i);
rem = (num % den);
add = rem / pow(10, i - 1);
total = total + (add * pow(10, count));
++i;
--count;
}
if (total == num) {
cout << "Palindrome"
<< "\n";
}
else {
cout << "Not a Palindrome"
<< "\n";
}
}
return 0;
}
please help me to know where I am going wrong in this code.
I don't understand your code. so i assumed by myself and wrote code.I assume that there will be no negative number and if there will be then i rid off negative sign. please provide desire output for negative number.
#include <iostream>
using namespace std;
int main()
{
//int num, rem, t, add;
int t;
cin >> t;
while (t-- > 0) {
int n;
cin >> n;
int num = abs(n);
if (n < 0)
{
n = abs(n);
}
int res{ 0 };
while (n > 0)
{
res *= 10;
int rem = n % 10;
res += rem;
n /= 10;
}
if (res == num) {
cout << "Palindrome"
<< "\n";
}
else {
cout << "Not a Palindrome"
<< "\n";
}
}
return 0;
}
ouptut of above code:
4
-191
Palindrome
232
Palindrome
123
Not a Palindrome
561
Not a Palindrome
Your code to reverse a number is very convoluted, as it uses pow (a floating point function) to get each digit. This is totally unnecessary if you look for the pattern of how to reverse an integer.
Simple addition, multiplying by 10, and modulus is all that's necessary to do this. Note that I created a function, so that it is easy to follow:
#include <cmath>
#include <iostream>
int reverse_int(int num)
{
int total = 0;
// take care of negative by using absolute value
int tempNum = abs(num);
while (tempNum > 0)
{
total = (total*10) + (tempNum % 10);
tempNum /= 10;
}
return (num < 0)?-total:total;
}
int main()
{
int num = 1234321;
if ( num == reverse_int(num))
std::cout << num << " is a palindrome\n";
else
std::cout << num << " is not a palindrome\n";
int num2 = 123;
if ( num2 == reverse_int(num2))
std::cout << num2 << " is a palindrome\n";
else
std::cout << num2 << " is not a palindrome\n";
}
Output:
1234321 is a palindrome
123 is not a palindrome
The loop is very simple if you follow what is going on:
number = 123 (Assume this is our number)
total = 0;
Loop while (number > 0):
First iteration:
total = (total * 10) + (number % 10) --> (0 * 10) + (0 % 3) --> 3
number /= 10 --> 12
Second iteration:
total = (total * 10) + (number % 10) = (3 * 10) + (12 % 10) --> 32
number /= 10 --> 1
Third iteration:
total = (total * 10) + (number % 10) = (32 * 10) + (1 % 10) --> 321
number /= 10 --> 0 (Stop the loop)
total = 321
At the end of the function, we just return the value, and make it negative if the original number was negative.
You are not checking if the input was valid. So if we leave that aside and assume the input is a valid integer then you can use a std::string and reverse it via std::reverse:
#include <string>
#include <algorithm>
#include <iostream>
int main() {
std::string input;
std::cin >> input;
std::string reverse = input;
std::reverse(reverse.begin(),reverse.end());
if (input == reverse) std::cout << "Palindrome number"
}
I am attempting to implement a program that reads a positive integer from the user and outputs all the perfect numbers between 2 and userNum. It also outputs all the pairs of amicable numbers that are between 2 and userNum. Both numbers must be within the range. I am seriously struggling with this.
Requirements:
1) calls to AnalyzeDivisors must be kept to theta(userNum) times all together. 2) Function void AnalyzeDivisors must take the following arguments int num, int& outCountDivs, int& outSumDivs. 3) Function bool IsPerfect must take the following argument int num.
I am honestly at a loss for how to do this within that efficiency range. I currently am able to determine all the perfect numbers in the range by bending the rules as far as parameters to the IsPerfect Function, but how can I determine amicable pairs without calling Analyze Dividors an inordinate amount of times each iteration of the for loop in main?
Any help would be greatly appreciated! Code below:
main
int main()
{
int userNum;
//Request number input from the user
cout << "Please input a positive integer num (>= 2): " << endl;
cin >> userNum;
for (int counter = 2; counter <= userNum; counter++)
{
//Set variables
int outCountDivs = 0, outSumDivs = 0, otherAmicablePair = 0;
bool perfectNum = false, isAmicablePair = false;
//Analyze dividors
AnalyzeDividors(counter, outCountDivs, outSumDivs);
//determine perfect num
perfectNum = IsPerfect(counter, outSumDivs);
if (perfectNum)
cout << endl << counter << IS_PERFECT_NUM;
}
return 0;
}
AnalyzeDividors
void AnalyzeDividors(int num, int& outCountDivs, int& outSumDivs)
{
int divisorCounter;
for (divisorCounter = 1; divisorCounter <= sqrt(num); divisorCounter++)
{
if (num % divisorCounter == 0 && num / divisorCounter != divisorCounter && num / divisorCounter != num)
{
//both counter and num/divisorCounter
outSumDivs += divisorCounter + (num / divisorCounter);
outCountDivs += 2;
}
else if ((num % divisorCounter == 0 && num / divisorCounter == divisorCounter) || num/divisorCounter == num)
{
//Just divisorCounter
outSumDivs += divisorCounter;
outCountDivs += 1;
}
}
}
IsPerfect
bool IsPerfect(int userNum, int outSumDivs)
{
if (userNum == outSumDivs)
return true;
else
return false;
}
I think I found a solution that fits the requirements. I found amicable numbers by storing every number and sum of divisors in a map. If a number's sum of divisors is entered in the map, and the sum of divisor's sum of divisors was the current number, then they are amicable.
Because the results are saved each time, you only call AnalyzeDivisors once per number.
Pardon the lazy variable naming.
#include <iostream>
#include <map>
#include <cmath>
void AnalyzeDivisors(int num, int& divc, int &divs)
{
divc = 1;
divs = 1;
for (int x = 2, y = std::sqrt(num); x <= y; ++x)
{
if (num % x == 0)
{
++divc;
divs += x;
if (num / x != x)
{
++divc;
divs += num / x;
}
}
}
}
bool IsPerfect(int num)
{
static std::map<int, int> amicable;
int divc = 0, divs = 0;
AnalyzeDivisors(num, divc, divs);
if (amicable.find(divs) != amicable.end() && amicable[divs] == num)
std::cout << num << " and " << divs << " are best bros for life.\n";
amicable[num] = divs;
return num == divs;
}
int main()
{
int num;
std::cout << "Pick a number: ";
std::cin >> num;
for (int x = 2; x < num; ++x)
{
if (IsPerfect(x))
std::cout << x << " is perfect in every way!\n";
}
}