Palindrome in repeated loop - c++

Checking 5 entries whether they're palindrome or not, the code i've written gives the correct output for the first entry but not the remaining ones. I've dry run the code yet couldn't find where the fault is.
Here's the code:
while (count < 5)
{
cin >> n;
store = n;
while (n > 0)
{
reverse = reverse * 10 + n % 10;
n = n / 10;
}
if (store == reverse)
cout << "it's a palindrome " << endl;
else
cout << "Not a palindrome " << endl;
count++;
}
All variables are of int data type

You should declare reverse inside first while loop because if you don't reverse will still hold the value from previous iteration and produce wrong result. As shown below:
while (count < 5)
{
cin >> n;
store = n;
int reverse=0; // <--- declare here;
while (n > 0)
{
reverse = reverse * 10 + n % 10;
n = n / 10;
}
if (store == reverse)
cout << "it's a palindrome " << endl;
else
cout << "Not a palindrome " << endl;
count++;
}

You're not resetting reverse between the runs. Add reverse = 0; at the beginning of your loop:
#include <iostream>
int main() {
int count = 0, store = 0, n = 0;
int reverse = 0;
while (count < 5)
{
reverse = 0;
std::cin >> n;
store = n;
while (n > 0)
{
reverse = reverse * 10 + n % 10;
n = n / 10;
}
if (store == reverse)
std::cout << "it's a palindrome " << std::endl;
else
std::cout << "Not a palindrome " << std::endl;
count++;
}
}

Related

Return biggest number after writing out coalltz sequence of given number

So if I write out a collatz sequence of the given number long int n in my first function then in the next I wanna return the biggest number how do I do take for example if I call the first writeCollatzSekvens(7) it writes out
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 and I wanna return 52.
void writeCollatzSekvens(long int n){
cout << n << " ";
while(n !=1){
if ( n % 2 == 0){
n = n/2;
cout << n << " ";
}
else{
n = (n*3) + 1;
cout << n << " ";
}
}
}
long int collatzMax(long int n){
int max = 0;
if (n > max){
max = n;
}
return max;
}
You have the following problem in your "collatzMax"-function:
long int collatzMax(long int n){
int max = 0; // max has now the value 0
if (n > max){ // Therefore we do here if (n > 0) and that is always true. N is always greater then 0
max = n; // This assignment will always been done, because the if is always true
// max is now n
}
return max; // The function will always return n
}
Your function is stateless. It does not remember the "old" max value. This will not work. It is anyway not called in your other function. And there it is needed.
If you want to have the max collatz number, then you need to calculate max-values in your main loop.
And, if you have calculated your max number in the main loop, you can return it at the end of the function.
This could then for example look like that:
#include <iostream>
long int writeCollatzSekvens(long int n) { // Changed function prototype. It will return a value now
long int maxNumber = 0;
std::cout << n << " ";
while (n != 1) {
// Continously check for a new max number
if (n > maxNumber) maxNumber = n;
if (n % 2 == 0) {
n = n / 2;
std::cout << n << " ";
}
else {
n = (n * 3) + 1;
std::cout << n << " ";
}
}
return maxNumber; // Return the calculated max collatz number
}
int main() {
long int mn = writeCollatzSekvens(7);
std::cout << "\n\nMax: " << mn << '\n';
}
Of course there are many other potential solutions
EDIT
If the function should be void, then we can add an additional output parameter maxNumber. And pass this parameter by reference or by pointer.
Please see the example below. using pointer:
#include <iostream>
void writeCollatzSekvens(long int n, long int* maxNumber) { // Changed function prototype. Use output pointer for max
*maxNumber = 0;
std::cout << n << " ";
while (n != 1) {
// Continously check for a new max number
if (n > *maxNumber) *maxNumber = n;
if (n % 2 == 0) {
n = n / 2;
std::cout << n << " ";
}
else {
n = (n * 3) + 1;
std::cout << n << " ";
}
}
}
int main() {
long int mn = 0;
writeCollatzSekvens(7, &mn);
std::cout << "\n\nMax: " << mn << '\n';
}
Using reference
#include <iostream>
void writeCollatzSekvens(long int n, long int& maxNumber) { // Changed function prototype. Use output reference for max
maxNumber = 0;
std::cout << n << " ";
while (n != 1) {
// Continously check for a new max number
if (n > maxNumber) maxNumber = n;
if (n % 2 == 0) {
n = n / 2;
std::cout << n << " ";
}
else {
n = (n * 3) + 1;
std::cout << n << " ";
}
}
}
int main() {
long int mn = 0;
writeCollatzSekvens(7, mn);
std::cout << "\n\nMax: " << mn << '\n';
}

How do i sum all numbers using loop?

For Example, I have number 1 + 6 + 7 + 12 + 13 + 18+.....+ n (n is the input from users which represent the number of elements) the index of this number starts from 1 by this it means​ that if the index is an odd number (1,3,5...) I want to increment the element at that index by 5 and if the index is an even number I want to increment the element at that index by 1 until I reach the of n number of elements. What I want is to sum all those numbers.
Sorry, It may hard to understand because of my poor English So let me write some of my C code here:
using namespace std;
int i, n, result = 0;
cout << "Input number to sum: ";
cin >> n;
// Finding result
for (i = 0; i <= n; i++){
if (i % 2 == 0) {
result +=i;
} else {
result += i * 5;
}
}
// Make last number have equal sign "1+6+7+12 = 36"
for (i = 0; i <= n; i++){
if (i == n) {
cout << i..?? << "=";
} else {
cout << i..?? << "+";
}
}
// Print result out
cout << result;
return 0;
}
Combine the computation with the output (I usually preach the opposite, but in this case it actually simplifies matters).
for (int i = 0; i <= n; i++)
{
int value = i % 2 == 0 ? i + 1 : i + 5;
cout << (i > 0 ? " + " : "") << value;
result += value;
}
cout << " = " << result;
I agree with the molbdnilo that combining calculations and output in this case, simplify the code.
I don't agree with the algorithm, though, given OP's description.
In the following the calculations are repeated to output the result
#include <iostream>
int main()
{
int n;
std::cout << "Input number to sum: ";
std::cin >> n;
auto update = [] (int i) { return i % 2 == 0 ? 1 : 5; };
int result = 0;
int value = 0;
for (int i = 0; i < n; i++)
{
value += update(i);
result += value;
}
std::cout << '\n';
for (int i = 0, value = 0; i < n; i++)
{
value += update(i);
std::cout << (i > 0 ? " + " : "") << value;
}
std::cout << " = " << result;
}
Testable here.
I agree with molbdnilo's answer. However the algorithm some changes.
The index starts from 1 , so value check for i in for loop should be
for (int i = 0; i < n; i++)
while updating the values, increment should be done on value and not on i.
Here is my solution:
using namespace std;
int main()
{
int i, n, result, value = 0;
cout << "Input number to sum: ";
cin >> n;
for (i = 0; i < n; i++)
{
value = i % 2 == 0 ? value + 1 : value + 5;
cout << (i > 0 ? " + " : "") << value;
result += value;
}
cout << " = " << result;
return 0;
}
Testable here

Binary search algorithm in c++

I am new to programming so please help me completing the task
the problem is:
After pressing y the while loop does not run again.
and secondly, how to print or get the array elements in descending order?
thank you!
#include <iostream>
using namespace std;
int main()
{
int item;
int flaging = 0;
int ind_low = 0;
int ind_high = 9;
int ind_mid = (ind_low + ind_high) / 2;
char conti;
//Array declaration and taking user input
int arr[10];
cout << "enter some values here : \n" << endl;
for (int i = 0; i < 10; i++)
{
cin >> arr[i];
}
// for sorthing the array
int temp;
for (int p = 1; p <= 9; p++)
for (int c = 0; c <= 8; c++)
if (arr[c] > arr[c + 1])
{
temp = arr[c];
arr[c] = arr[c + 1];
arr[c + 1] = temp;
}
do {
//asking for searching
cout << "Enter the value you want to search : " << endl;
cin >> item;
while (ind_low <= ind_high)
{
if (item == arr[ind_mid])
{
cout << "At " << ind_mid << " index the value " << item << " is found " << endl;
flaging++;
break;
}
if (item < arr[ind_mid])
{
ind_high = ind_mid - 1;
ind_mid = (ind_low + ind_high) / 2;
}
else
{
ind_low = ind_mid + 1;
ind_mid = (ind_low + ind_high) / 2;
}
}
if (flaging == 0)
{
cout << "Value not found" << endl;
}
cout << "To search again press 'y', to exit press any key" << endl;
cin >> conti;
} while ((conti == 'y') || (conti == 'Y'));
}
when I ran it on my pc after pressing y it did run again, can you provide the input that failed you?
for the second question what do you mean?
you can do a for loop that goes like this:
for(int index = ARR_SIZE -1 ; index >= 0 ; --index){
cout << array[index];
}
edit: I understand what you mean. after each run you should reset your indexes otherwise you will always run on the same once:
before you end the loop the values should be reseted.
ind_low = 0;
ind_high = 9;
ind_mid = (ind_low + ind_high) / 2;
that gonna print the array from end to start.

Palindromes And Project Euler C++ Version -Tips

Can Anyone Tell Me What's Wrong In My Code?
Thank you :)
// A palindromic number reads the same both ways.
// The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
// Find the largest palindrome made from the product of two 3-digit numbers.
#include <iostream>
using namespace std;
int main()
{
int x = 2;
int product;
int n, digit, rev = 0;
int greatest = 0;
for(int i = 2;i<100;i++){
product = x * i;
n = product;
cout << x << " * " << i << " = " << product << endl;
do
{
digit = product % 10;
rev = (rev * 10) + digit;
product = product / 10;
} while(product != 0);
cout << " The reverse of the number is: " << rev << endl;
if(n == rev){
cout << "Therefore Palindrome" << endl;
if(rev > greatest){
cout << "REV Greater Than Greatest Palindrome" << endl;
greatest = rev;
}
}
if(i == 99){
if(x < 99){
x++;
i = 1;
cout << "Go For The Next Loop" << endl;
}
}
}
cout << "The Greatest Palindrome Number Is " << greatest << endl;
return 0;
}
Several things:
You should be counting down from 999 thru 100.
You should be using two loops for the two factors of your product
rev should be initially zero before each entrance into your inner do-while loop
The results would look something like this, with all but the detected palindromes and final result being output (the amount of worthless noise in your output is mind-bending)
#include <iostream>
using namespace std;
int main()
{
int product;
int n, digit, rev = 0;
int greatest = 0;
for(int i = 999;i>=100; --i)
{
for (int j =999; j>=100; --j)
{
product = j * i;
n = product;
rev = 0;
do
{
rev = (rev * 10) + (product % 10);
product /= 10;
} while(product != 0);
if(n == rev)
{
cout << "Palindrome : " << i << " * " << j << " = " << n << endl;
if(rev > greatest)
greatest = rev;
}
}
}
cout << "The Greatest Palindrome Number Is : " << greatest << endl;
return 0;
}
This will conclude the correct answer you seek.
Faster
Optionally, you can squeeze better performance out of this by understanding a few additional details:
The task is to find the largest palindrome, not just the longest palindrome. Therefore, once you find one, any product, palindrome or not, that is a smaller magnitude than the current largest palindrome is pointless to even check and the inner loop can be terminated (thus the reason you're counting down).
A little number crunching will allow you to conclude that at least one of the factors must be divisible by 11. I won't cover why, but do the math, it's true. Therefore, you can make one of your loops a count-down from the largest 3-digit multiple of 11 (990) to 100, in steps of (-11).
The result looks like this:
#include <iostream>
using namespace std;
int main()
{
int greatest = 0;
for(int i = 999;i>=100; --i)
{
for (int j =990; j>=100; j-=11)
{
int product = j * i;
if (product < greatest)
break;
int n = product;
int rev = 0;
do
{
rev = (rev * 10) + (product % 10);
product /= 10;
} while(product != 0);
if(n == rev)
{
cout << "Palindrome : " << i << " * " << j << " = " << n << endl;
if(rev > greatest)
greatest = rev;
}
}
}
cout << "The Greatest Palindrome Number Is : " << greatest << endl;
return 0;
}
Output
Palindrome : 995 * 583 = 580085
Palindrome : 993 * 913 = 906609
The Greatest Palindrome Number Is : 906609

Finding factors of a number. Not getting accurate results

Can someone help correct my algorithm? I've tested it on a few numbers, and it doesn't output the complete factorization. For numbers with a large number of factors, it just completely fails.
int num = 20;
for(int i = 2; i <= num; i++)
{
if(num%i == 0)
{
cout << i << endl;
cout << num << endl;
num = num/i;
}
}
EDIT: The two answers provided did not work, still not getting full results.
EDIT2: Divisors VS Factors
Judging from you comment to #Luchian Grigore, you're confusing divisors with (prime) factorization. Divisors of a number are all numbers for which num % i == 0 is true. Factorization means getting a representation of num by a product of smaller numbers. If you want uniqueness of factorization, you usually use prime factorization.
To get all the divisors your code should be
for ( int i = 1; i <= num; ++i ) // note that 1 and num are both trivially divisors of num
{
if ( num % i == 0 ) // only check for divisibility
{
std::cout << i << std::endl;
}
}
to get the (prime) factorization, it's
for ( int i = 2; i <= num; ++i )
{
while ( num % i == 0 ) // check for divisibility
{
num /= i;
std::cout << i << std::endl;
}
// at this point, i cannot be a divisor of the (possibly modified) num.
}
The problem is that you're increasing i even if it is a divisor, and you shouldn't unless you find all its occurences.
So, for 4, you'd have 2 twice. But after the first 2 you encounter, you exit the loop because i is incremented to 3 and num became 2.
The following should work:
for(int i = 2; i <= num; )
{
if(num%i == 0)
{
cout << i << endl;
cout << num << endl;
num = num/i;
}
else
{
i++;
}
}
for(int i = 2; i <= num; i++)
{
if(num%i == 0)
{
cout << i << endl;
cout << num << endl;
num = num/i;
i--; // Add this to account for multiple divisors
}
}
for(int i = 2; i <= num; i++)
{
if(num%i == 0)
{
cout << i << endl;
cout << num << endl;
}
}
This should work. Note, should use c++11 for move constructor, otherwise you are going to want to pass in a std::list& instead.
std::list<int64_t> factor(int64_t f)
{
std::list<int64_t> factors;
for(int64_t ii = 2; ii<=f; ii++) {
while(f % ii == 0) {
f = f/ii;
factors.push_back(ii);
}
}
return factors;
}