Palindromes And Project Euler C++ Version -Tips - c++

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

Related

How to find Maximum number and negative numbers from a .txt file and also how to output Total result to another .txt file

I want to find Maximum numbers from my "numbers.txt" file and amount of negative numbers. And i want to output the Total result to another .txt file and console and the rest to the console only.
Im very new and just cant figure out how to do it.
This is what i have now
a "numbers.txt" file with
-4
53
-5
-3
2
and
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int n = 0;
int sum = 0, total = 0;
fstream file("numbers.txt");
while (file >> n)
{
sum += n;
total++;
}
int average = (float)sum / total;
int AmountOfNumbersAdded = total;
int Highest;
int Negative;
cout << "Total result: " << sum << endl;
cout << "Numbers added: " << AmountOfNumbersAdded << endl;
cout << "Average number: " << average << endl;
cout << "Maxiumum number: " << endl;
cout << "Negative numbers: " << endl;
return 0;
}
i tried to do
float Highest = INT_MIN;
if (Highest < num[i]) {
Highest = num[i];
but it just wouldn't work.
You don't need to store the numbers to find the maximum or the amount of negative numbers, but you need to track them inside the loop, like you're already doing with the sum and the total amount of numbers.
int Highest = INT_MIN;
int Negative = 0;
while (file >> n)
{
sum += n;
total += 1;
if (n < 0)
{
Negative += 1;
}
if (n > Highest)
{
Highest = n;
}
}
float average = (float)sum / total;
Here's what you're looking for.
#include <iostream>
#include <fstream>
int main()
{
int n = 0;
int sum = 0, total = 0;
int highest = 0;
int negatives = 0;
std::fstream file("numbers.txt");
while (file >> n)
{
if (n > highest) highest = n;
if (n < 0) ++negatives;
sum += n;
++total;
}
int average = (float)sum / total;
int AmountOfNumbersAdded = total;
std::cout << "Total result: " << sum << "\n";
std::cout << "Numbers added: " << AmountOfNumbersAdded << "\n";
std::cout << "Average number: " << average << "\n";
std::cout << "Maxiumum number: " << highest << "\n";
std::cout << "Negative numbers: " << negatives << "\n";
file.close();
return 0;
}
As you're new, few advices for you:
Never use using namespace std.
Prefer using "\n" instead of std::endl.
Don't forget to close any files/database after opening them like you did in your code.
Always try to avoid macros.

C++ nested loop prime number

I have a question that I couldn’t solve , I worked hard and didn’t have a total solution
I need to type a number of soldiers and check out if the
serial numbers product = the number of soldiers
and
check if one of the serial numbers is PRIME.
As a result I need to print the 2 serial numbers that bring me the product once
For example:
Number = 20
I need to print
2 10
4 5
Number = 120
I need to print
2 60
3 40
5 24
6*20 Cant be printed because none of them is prime number
and so on
Number = 48
I need to print
2 24
3 16
4*12 Cant be printed because none of them is prime number
And so on
I did everything alright except finding if one of the numbers is prime
the code is :
int armysize;
cout << "Please type how many soldiers do you have in your army:" << endl;
cin >> armysize;
int serialnumproduct = 0;
for (int soldiernum = 2; soldiernum < sqrt(armysize); soldiernum++)
{
for (int nextsoldier = 2; nextsoldier <= armysize/2; nextsoldier++)
{
serialnumproduct = soldiernum * nextsoldier;
if (serialnumproduct == armysize && soldiernum != nextsoldier)
cout << soldiernum << " * " << nextsoldier << " = " <<
serialnumproduct << endl;
}
}
return 0;
A function such as this one should tell you wether a number is prime or not. You need to make sure you are dealing with numbers that can fit in an int on your machine, or update the code
bool IsPrime (int ninteger)
{
bool prime (true);
for(auto i = 2 ; i<ninteger ; ++i)
{
if (ninteger%i == 0)
prime = false;
}
return prime;
}
Basically what you need is a function to show if soldiernum is a prime number or not. I used a prime_test() function and used it on line 34 as an if() statement, so the code see if it should use the soldiernum or not.
This was the result:
Please type how many soldiers do you have in your army:
400
2 * 200 = 400
5 * 80 = 400
#include <iostream>
#include <conio.h>
#include <math.h>
using namespace std;
bool prime_test (int num)
{
bool prime (true);
for(int i = 2 ; i<num; ++i)
{
if (num%i == 0)
prime = false;
}
return prime;
}
int main(){
int armysize;
int count=2;
bool isPrime = true;
cout << "Please type how many soldiers do you have in your army:" << endl;
cin >> armysize;
int serialnumproduct = 0;
for (int soldiernum = 2; soldiernum < sqrt(armysize); soldiernum++){
for (int nextsoldier = 2; nextsoldier <= armysize/2; nextsoldier++)
{
serialnumproduct = soldiernum * nextsoldier;
if (serialnumproduct == armysize && soldiernum != nextsoldier)
if(prime_test(soldiernum)==true) {
cout << soldiernum << " * " << nextsoldier << " = " <<
serialnumproduct << endl;
}
}
}
return 0;
}

Palindrome in repeated loop

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++;
}
}

Classifying digits of an integer value

I spent a day on this code for count even and zero and odd numbers
From long datatype I used a function to send data. Here is the code
#include <iostream>
using namespace std;
void digitCount(long long int &num);
int main ()
{
long long int num;
cout <<"Enter any No. " <<endl;
cin >>num;
cout <<endl;
digitCount(num);
return 0;
}
void digitCount(long long int &num)
{
int e = 0, z = 0, o = 0, x = 0;
for (int i = 0; i <= num; i++)
{
x= num % 10;
if(x == 0)
{
++z;
num = num / 10;
}
else if(x%2==1)
{
++o;
num = num / 10;
}
else
{
++e;
num = num / 10;
}
}
cout << "No of zeros Digits = " << z<< endl;
cout << "No of odd Digits = " << o << endl;
cout << "No of Even Digits = " << e << endl;
}
the problem is when I count odd numbers there is a number missed
for example when i input : 12345
the result is
no of even : 2
no of odd : 2 (should be 3)
no of zero : 0
and here the question :
Write a function that takes as parameter an integer (as a long value) and returns the number of odd, even, and zero digits. Also write a program to test your function. Use pass by reference method.
Instead of the for loop you should use:
while (num > 0)
You're constantly changing num and when it gets to 1 (in your 12345 example), i is at 3. I also modified your digitcount to demonstrate some decent formatting for readable code.
void digitCount(long long int &num) {
int e(0), z(0), o(0), x(0);
while (num > 0) {
x = num % 10;
if (x == 0) {
z++;
}
else if (x % 2 == 1) {
o++;
}
else {
e++;
}
num /= 10;
}
cout << "No of zeros Digits = " << z << endl;
cout << "No of odd Digits = " << o << endl;
cout << "No of Even Digits = " << e << endl;
}
If you believe this solves your problem && is the best answer, please click the checkmark next to this answer. Thanks

I need to find the location of certain digits from user input

I have been trying to finish this code (function) for a while now, but am stuck on the last part. In this code, I prompt the user to select a number of integers and any number of digits and then find the smallest and largest value within these digits. On the next part, I am supposed to determine which of the given digits the smallest and largest are located such that the output should be:
Digit _ can be found in integer number(s): _, _
I apologize in advance if my code is sloppy; I just started learning C++ and haven't fully grasped the language yet.
int digitSizeLoca() {
int userNumInteger;
int* iPtr;
int* iPtr2;
int* iPtr3;
int value;
int value2;
int value3;
std::cout << "\nHow many integers? ";
std::cin >> userNumInteger;
iPtr = new int[userNumInteger];
iPtr2 = new int[userNumInteger];
iPtr3 = new int[userNumInteger];
for (int i = 0; i < userNumInteger; i++) {
*(iPtr3 + 1) = *(iPtr2 + 1) = *(iPtr + 1);
std::cout << "\nEnter digit #" << i + 1 << ": ";
std::cin >> *(iPtr + 1);
}
value = *(iPtr + 1);
value2 = *(iPtr2 + 1);
value3 = *(iPtr3 + 1);
if (value != 0, value2 != 0, value3 != 0) {
if (value <= 0)
value = -value;
if (value2 <= 0)
value2 = -value2;
if (value3 <= 0)
value3 = -value3;
int lDigit;
int sDigit;
int curDigit;
int pot = 10;
lDigit = sDigit = value % pot;
while (value, value2, value3) {
if (value / pot == 0, value2 / pot == 0, value3 / pot == 0) break;
curDigit = (value / pot, value2 / pot, value3 / pot) % 10;
if (curDigit < sDigit)
sDigit = curDigit;
if (curDigit > lDigit)
lDigit = curDigit;
pot*=10;
}
std::cout << "\nThe smallest digit: " << sDigit << std::endl
<< "\n Digit " << sDigit
<< " can be found in integer number(s): ";
std::cout << "\nThe largest digit: " << lDigit << std::endl
<< "\n Digit " << lDigit
<< " can be found in integer number(s): ";
}
return 0;
}
Example of what output should be given user input:
If user chooses 2 for userNumInteger, and inputs the digit values 1234 and -1578,
the output for my question should be:
Smallest digit: 1
Digit 1 can be found in integer number(s): 1, 2
.
.
.
Thank you!
If digits matter, then input 02 is not the same as 2 (even if both means the number 2; beware that 02 could be an octal notation). So you should read a std::string, check that it has digits appropriately using isdigit, then use std::stol (in C++11) or strtol to do the conversion.
You'll better use some std::vector<int> instead of initializing a pointer with new int[userNumInteger] ...
Since you mentioned that you can only use integer for now, it makes your life a bit difficult. Basile was right when he mentioned that you should use string. That would help you iterating through the numbers over and over again like I did below but it does the task - the drawback being that you will have to iterate 3 times but if you do not want to sort or do anything special then it is good enough....
int digitSizeLoca()
{
int userNumInteger;
int* iPtr;
int lowest = 9;
int highest = 0;
std::cout << "\nHow many integers? ";
std::cin >> userNumInteger;
iPtr = new int[userNumInteger];
for (int i = 0; i < userNumInteger; i++)
{
std::cout << "\nEnter digit #" << i + 1 << ": ";
std::cin >> *(iPtr + i);
}
for (int i = 0; i < userNumInteger; i++)
{
int number = *(iPtr + i);
std::cout << "You Entered (" << i << "): " << *(iPtr + i) << std::endl;
do
{
int remainder = number % 10;
if (remainder > highest) highest = remainder;
if (remainder < lowest) lowest = remainder;
number = number / 10;
}
while (number > 0);
}
std::cout << "\nThe largest digit: " << highest << std::endl
<< " can be found in integer number(s): ";// Notice no endl here
for (int i = 0; i < userNumInteger; i++)
{
int number = *(iPtr + i);
do
{
int remainder = number % 10;
if (remainder == highest)
{
std::cout << (i+1) << ",";
break;
}
number = number / 10;
}
while (number > 0);
}
std::cout << std::endl;
std::cout << "\nThe smallest digit: " << lowest << std::endl
<< " can be found in integer number(s): ";// Notice no endl here
for (int i = 0; i < userNumInteger; i++)
{
int number = *(iPtr + i);
do
{
int remainder = number % 10;
if (remainder == lowest)
{
std::cout << (i+1) << ",";
break;
}
number = number / 10;
}
while (number > 0);
}
std::cout << std::endl;
}