C++ prints all the combination of numbers with the same digits - c++

So, I need to implement TheSameDigit() function, basically this function needs to print out all combinations of numbers that has the same digits. TheSameDigit function MUST be recursive and use NoDigits() and DelDigit() functions.
NoDigits(int x) => This function will return the number of digits
input: 123, output: 3
DelDigit(int x, int delD) => This function return an int which value is x, but having the delD-digit removed.
input: x = 789, delD = 2, output = 79
TheSameDigit() => The function to prints the combination of numbers with the same digits(it does not work currently).
Input: 123
Output:
123
231
132
312
213
321
#include <iostream>
using namespace std;
int NoDigits(int x);
int DelDigit(int x, int delD);
void TheSameDigits(int x, int i, int origin, bool firstTime);
int main() {
int num;
cout << "Please input an integer: ";
cin >> num;
cout << "All integers have the same digits with " << num << " are: " << endl;
TheSameDigits(num, 1, num, 1);
}
int NoDigits(int x) {
if (x == 0) {
return 0;
}
return 1 + NoDigits(x / 10);
}
int DelDigit(int x, int delD) {
int size = NoDigits(x);
int reverse = 0;
for (int i = 0; x != 0; i++, x /= 10) {
if (i != size - delD) {
int digit = x % 10;
reverse = reverse * 10 + digit;
}
}
int newNum = 0;
for (int i = 0; reverse != 0; i++, reverse /= 10) {
int digit = reverse % 10;
newNum = newNum * 10 + digit;
}
return newNum;
}
void TheSameDigits(int x, int i, int origin, bool firstTime) {
const int size = NoDigits(origin);
// Base case
if (origin == x && !firstTime) {
return;
}
if (i == size) {
i = 1;
}
// Find the removed digit
int temp = x;
int removedDigit;
for (int j = 0; temp > 0; j++, temp /= 10) {
if (j == size - i) {
removedDigit = temp % 10;
break;
}
}
// Calculate the next combination
int nextNum = (DelDigit(x, i) * 10) + removedDigit;
cout << nextNum << endl;
TheSameDigits(nextNum, i + 1, origin, false);
}
Can someone help me implement TheSameDigit function or give me an idea about it?
Thank you!

Related

I'm having problems looping a function

funtion
I have been trying too loop the "1 + 1/3 + 1/5 + ... + 1/n" part in the screenshot inside my code but could not do it all.
The compiler calculates 'x' which is the factorial correctly the only problem for me now is looping the fractions in the function.
int main()
{
int i=1,n,x=1; //x : factorial
double f;
cout<<"Enter an odd number : "<<endl;
cin>>n;
if (n%2==0)
{
cout<<"You have to enter an odd number."<<endl;
}
else
{
while(i<=n)
{
x = x * i;
f = x*(1+(1.0/n)) ;
i+=1;
}
}
cout<<"f = "<<f<<endl;}
Here is your answer
#include <iostream>
using namespace std;
int main()
{
int n;
double f = 1;
cout<<"Enter an odd number : "<<endl;
cin >> n;
if ( n%2 == 1)
{
double temp = n;
while ( temp > 1 ) // this one calculates factorial,
{
f *= temp;
temp--;
} // f = n!
temp = 1;
double result = 0;
while ( temp <= n ) // this one calculates (1 + 1/3 + ... + 1/n)
{
result += ( 1 / temp );
temp += 2;
} // result = (1 + 1/3 + ... + 1/n)
f = f * result; // f = n! * (1 + 1/3 + ... + 1/n)
cout<<"f = "<<f<<endl;
}
else
cout<<"You have to enter an odd number."<<endl;
return 0;
}
You need to operate on the same types of data ;)
Hey I have Modified your code, you can run it and can match your Result with Calulator
#include <iostream>
#include <math.h>
using namespace std;
int odnumber(int num);
int calFactorial(int num);
int main() {
int oddNumber, i = 1;
float temp=0, temp2 = 0, f = 0.0;
do
{
cout << "Enter the Odd Number: " << endl;
cin >> oddNumber;
} while (oddNumber%2 == 0);
while (i <= oddNumber)
{
if (odnumber(i))
{
temp = (double)(1.0/i);
temp2 +=temp;
}
i++;
}
f = calFactorial(oddNumber)*temp2;
cout << "F is = " << f << endl;
return 0;
}
int odnumber(int num) {
if (num % 2 != 0)
{
return 1;
}
else
{
return 0;
}
}
int calFactorial(int num) {
int x = 1, i = 1; //x is Factorial
while (i <= num)
{
x = x * i;
i++;
}
return x;
}
This is the Output: Run on my Machine

Print prime factorization in exponential form in C++

So far I have this code. I'm trying to print prime factorization with exponents. For example, if my input is 20, the output should be 2^2, 5
#include <iostream>
#include <cmath>
using namespace std;
void get_divisors (int n);
bool prime( int n);
int main(int argc, char** argv) {
int n = 0 ;
cout << "Enter a number and press Enter: ";
cin >>n;
cout << " Number n is " << n << endl;
get_divisors(n);
cout << endl;
return 0;
}
void get_divisors(int n){
double sqrt_of_n = sqrt(n);
for (int i =2; i <= sqrt_of_n; ++i){
if (prime (i)){
if (n % i == 0){
cout << i << ", ";
get_divisors(n / i);
return;
}
}
}
cout << n;
}
bool prime (int n){
double sqrt_of_n = sqrt (n);
for (int i = 2; i <= sqrt_of_n; ++i){
if ( n % i == 0) return 0;
}
return 1;
}
I hope someone can help me with this.
You can use an std::unordered_map<int, int> to store two numbers (x and n for x^n). Basically, factorize the number normally by looping through prime numbers smaller than the number itself, dividing the number by the each prime as many times as possible, and recording each prime you divide by. Each time you divide by a prime number p, increment the counter at map[p].
I've put together a sample implementation, from some old code I had. It asks for a number and factorizes it, displaying everything in x^n.
#include <iostream>
#include <unordered_map>
#include <cmath>
bool isPrime(const int& x) {
if (x < 3 || x % 2 == 0) {
return x == 2;
} else {
for (int i = 3; i < (int) (std::pow(x, 0.5) + 2); i += 2) {
if (x % i == 0) {
return false;
}
}
return true;
}
}
std::unordered_map<int, int> prime_factorize(const int &x) {
int currentX = abs(x);
if (isPrime(currentX) || currentX < 4) {
return {{currentX, 1}};
}
std::unordered_map<int, int> primeFactors = {};
while (currentX % 2 == 0) {
if (primeFactors.find(2) != primeFactors.end()) {
primeFactors[2]++;
} else {
primeFactors[2] = 1;
}
currentX /= 2;
}
for (int i = 3; i <= currentX; i += 2) {
if (isPrime(i)) {
while (currentX % i == 0) {
if (primeFactors.find(i) != primeFactors.end()) {
primeFactors[i]++;
} else {
primeFactors[i] = 1;
}
currentX /= i;
}
}
}
return primeFactors;
}
int main() {
int x;
std::cout << "Enter a number: ";
std::cin >> x;
auto factors = prime_factorize(x);
std::cout << x << " = ";
for (auto p : factors) {
std::cout << "(" << p.first << " ^ " << p.second << ")";
}
}
Sample output:
Enter a number: 1238
1238 = (619 ^ 1)(2 ^ 1)
To begin with, avoid using namespace std at the top of your program. Second, don't use function declarations when you can put your definitions before the use of those functions (but this may be a matter of preference).
When finding primes, I'd divide the number by 2, then by 3, and so on. I can also try with 4, but I'll never be able to divide by 4 if 2 was a divisor, so non primes are automatically skipped.
This is a possible solution:
#include <iostream>
int main(void)
{
int n = 3 * 5 * 5 * 262417;
bool first = true;
int i = 2;
int count = 0;
while (i > 1) {
if (n % i == 0) {
n /= i;
++count;
}
else {
if (count > 0) {
if (!first)
std::cout << ", ";
std::cout << i;
if (count > 1)
std::cout << "^" << count;
first = false;
count = 0;
}
i++;
if (i * i > n)
i = n;
}
}
std::cout << "\n";
return 0;
}
Note the i * i > n which is an alternative to the sqrt() you are using.

Recursively storing integers in an array

I have problem with recursive functions.
I have to build a recursive function which creates an array of integer values corresponding to the digits of a given number.
For example, if I input a number like 3562, it should look like :
myArray[0] = 3
myArray[1] = 5
myArray[2] = 6
myArray[3] = 2
Here is my code :
#include <iostream>
using namespace std;
int myFunction(int num, int lenOfNum);
int main(){
int number;
int lengthCount = 0;
cout <<"Input numbers" << endl;
cin >> number;
int temp = number;
for(; number != 0; number /= 10, lengthCount++);
number = temp;
cout << myFunction(number, lengthCount) << endl;
}
int myFunction(int num, int lenOfNum){
int arr[lenOfNum];
if(num > 0){
for(int i = 0; i < lenOfNum; i++){
arr[i] = num/=10;
cout << "arr[" << i + 1 << " ]= " << arr[i] << endl;
}
return myFunction(num, lenOfNum);
}
else if(num == 0){
return 0;
} else;
}
The problem with your code is that you are calling int arr[lenOfNum] in each method call, which in short creates an array with a new reference to a memory location that can store lenOfNum integers.
To solve this, we declare the array in the main method and pass it as a parameter to the function.
int main() {
// somewhere in main after reading lenOfNum
int arr[lenOfNum];
// somewhere in main after declaring an array
myFunction(arr, number, lengthCount - 1);
}
and myFunction as
void myFunction(int *arr, int num, int idx) {
if (idx < 0) return; // you've completed processing the num
else if (num == 0) {
arr[0] = 0;
return;
}
arr[idx--] = num % 10;
myFunction(arr, num / 10, idx);
}
Using vector and rest part of your example
#include <iostream>
using namespace std;
void myFunction(vector<int> &arr, int num, int lenOfNum){
if (num < 0) {
return;
}
else if (num == 0) {
return;
}
int next_idx = lenOfNum - 1;
int digit = num % 10;
arr[next_idx] = digit;
myFunction(arr, num / 10, next_idx);
}
int main(){
int number;
int lengthCount = 0;
cout <<"Input numbers" << endl;
cin >> number;
int temp = number;
for(; number != 0; number /= 10, lengthCount++);
number = temp;
auto arr = vector<int>(lengthCount, 0);
myFunction(arr, number, lengthCount);
for(int i = 0; i < arr.size(); i++){
cout << "arr[" << i << " ]= " << arr[i] << endl;
}
}
Works for positive numbers
#include <vector>
#include <stdio.h>
std::vector<int> myFunction(int num)
{
std::vector<int> ret;
int irec = num / 10;
if (irec > 0)
ret = myFunction(irec);
ret.push_back('0' + (num % 10));
return ret;
}
int main(int argc, char *argv[])
{
std::vector<int> res = myFunction(539);
for(unsigned int i = 0; i < res.size(); i++)
printf("%c,", res[i]);
}

Program that checks whether another number is contained within it

I've just recently started to dabble in coding, and I ran into a problem that I haven't been able to solve for days, and the closest thing I've been able to find online is a program checking whether a number contains a specific digit, but that doesn't really apply in my case, I don't think. The problem is to let the user enter two positive numbers and check whether the reverse of the second number is contained within the first one. For example if you enter 654321 and 345, it would say say that it contains it because the reverse of 345 is 543 and 654321 contains that. Here's what I've been trying, but it has been a disaster.
P.S: The variables should stay integer through the program.
#include <iostream>
using namespace std;
bool check(int longer, int shorter)
{
int i = 1;
int rev=0;
int digit;
while (shorter > 0)
{
digit = shorter%10;
rev = rev*10 + digit;
shorter = shorter/10;
}
cout << rev << endl;
bool win=0;
int left = longer / 10; //54321
int right = longer % 10; // 65432
int middle = (longer /10)%10; // 5432
int middle1;
int middle2;
int trueorfalse = 0;
while (left > 0 && right > 0 && middle1 > 0 && middle2 >0)
{
left = longer / 10; //4321 //321
right = longer % 10; //6543 //654
middle1 = middle%10; //543
middle2= middle/10; //432
if (rev == left || rev == right || rev == middle1 || rev == middle2 || rev == middle)
{
win = true;
}
else
{
win = false;
}
}
return win;
}
int main ()
{
int longer;
int shorter;
int winorno;
cout << "Please enter two numbers, first of which is longer: ";
cin >> longer;
cin >> shorter;
winorno = check(longer,shorter);
if (winorno==true)
{
cout << "It works.";
}
else
{
cout << "It doesn't work.";
}
return 0;
}
The more you overthink the plumbing, the easier it is to
stop up the drain. -- Scotty, Star Trek III.
This becomes much easier if you divide this task in two parts:
Reverse the digits in an integer.
Search the second integer for the reversed integer calculated by the first part.
For the first part, assume that n contains the number to reverse.
int modulo=1;
int reversed_n=0;
do
{
reversed_n = reversed_n * 10 + (n % 10);
modulo *= 10;
} while ( (n /= 10) != 0);
The end result is if n contained 345, reversed_n will end up with 543, and modulo will be 1000. We'll need modulo for the second part.
The reason the loop is structured this way is intentional. If the original number is 0, we want to wind up with reversed_n also 0, and modulo as 10.
And now, we can take a similar approach to search the second number, called search, whether it contains reversed_n:
for (;;)
{
if ((search % modulo) == reversed_n)
{
std::cout << "Yes" << std::endl;
return 0;
}
if (search < modulo)
break;
search /= 10;
}
std::cout << "No" << std::endl;
Complete program:
#include <iostream>
int main()
{
int search=654321;
int n=345;
int modulo=1;
int reversed_n=0;
do
{
reversed_n = reversed_n * 10 + (n % 10);
modulo *= 10;
} while ( (n /= 10) != 0);
for (;;)
{
if ((search % modulo) == reversed_n)
{
std::cout << "Yes" << std::endl;
return 0;
}
if (search < modulo)
break;
search /= 10;
}
std::cout << "No" << std::endl;
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
int calculateNumLength(int num){
int length = 0;
while (num > 0) {
num = num / 10;
length++;
}
return length;
}
bool check(int longer, int shorter){
int reversed = 0;
int digit;
int shortLength = calculateNumLength(shorter);
int longLength = calculateNumLength(longer);
int diffrence = longLength - shortLength;
int possibleValues = diffrence + 1;
int possibleNums[possibleValues];
while ( shorter > 0 ) {
digit = shorter % 10;
rev = ( rev * 10 ) + digit;
shorter = shorter / 10;
}
int backstrip = pow(10, diffrence);
int frontstrip = pow(10, longLength-1);
int arrayCounter = 0;
while ( longer > 0 ){
possibleNums[arrayCounter++] = longer/backstrip;
if ( backstrip >= 10 ){
backstrip = backstrip / 10;
}else{
break;
}
longer = longer % frontstrip;
frontstrip = frontstrip / 10;
}
for (int i=0;i<possibleValues;i++){
if (possibleNums[i] == rev ){
return true;
}
}
return false;
}
int main() {
std::cout << check(654321,123) << std::endl;
return 0;
}

C++ get each digit in int

I have an integer:
int iNums = 12476;
And now I want to get each digit from iNums as integer. Something like:
foreach(iNum in iNums){
printf("%i-", iNum);
}
So the output would be: "1-2-4-7-6-".
But i actually need each digit as int not as char.
Thanks for help.
void print_each_digit(int x)
{
if(x >= 10)
print_each_digit(x / 10);
int digit = x % 10;
std::cout << digit << '\n';
}
Convert it to string, then iterate over the characters. For the conversion you may use std::ostringstream, e.g.:
int iNums = 12476;
std::ostringstream os;
os << iNums;
std::string digits = os.str();
Btw the generally used term (for what you call "number") is "digit" - please use it, as it makes the title of your post much more understandable :-)
Here is a more generic though recursive solution that yields a vector of digits:
void collect_digits(std::vector<int>& digits, unsigned long num) {
if (num > 9) {
collect_digits(digits, num / 10);
}
digits.push_back(num % 10);
}
Being that there are is a relatively small number of digits, the recursion is neatly bounded.
Here is the way to perform this action, but by this you will get in reverse order.
int num;
short temp = 0;
cin>>num;
while(num!=0){
temp = num%10;
//here you will get its element one by one but in reverse order
//you can perform your action here.
num /= 10;
}
I don't test it just write what is in my head. excuse for any syntax error
Here is online ideone demo
vector <int> v;
int i = ....
while(i != 0 ){
cout << i%10 << " - "; // reverse order
v.push_back(i%10);
i = i/10;
}
cout << endl;
for(int i=v.size()-1; i>=0; i--){
cout << v[i] << " - "; // linear
}
To get digit at "pos" position (starting at position 1 as Least Significant Digit (LSD)):
digit = (int)(number/pow(10,(pos-1))) % 10;
Example: number = 57820 --> pos = 4 --> digit = 7
To sequentially get digits:
int num_digits = floor( log10(abs(number?number:1)) + 1 );
for(; num_digits; num_digits--, number/=10) {
std::cout << number % 10 << " ";
}
Example: number = 57820 --> output: 0 2 8 7 5
You can do it with this function:
void printDigits(int number) {
if (number < 0) { // Handling negative number
printf('-');
number *= -1;
}
if (number == 0) { // Handling zero
printf('0');
}
while (number > 0) { // Printing the number
printf("%d-", number % 10);
number /= 10;
}
}
Drawn from D.Shawley's answer, can go a bit further to completely answer by outputing the result:
void stream_digits(std::ostream& output, int num, const std::string& delimiter = "")
{
if (num) {
stream_digits(output, num/10, delimiter);
output << static_cast<char>('0' + (num % 10)) << delimiter;
}
}
void splitDigits()
{
int num = 12476;
stream_digits(std::cout, num, "-");
std::cout << std::endl;
}
I don't know if this is faster or slower or worthless, but this would be an alternative:
int iNums = 12476;
string numString;
stringstream ss;
ss << iNums;
numString = ss.str();
for (int i = 0; i < numString.length(); i++) {
int myInt = static_cast<int>(numString[i] - '0'); // '0' = 48
printf("%i-", myInt);
}
I point this out as iNums alludes to possibly being user input, and if the user input was a string in the first place you wouldn't need to go through the hassle of converting the int to a string.
(to_string could be used in c++11)
I know this is an old post, but all of these answers were unacceptable to me, so I wrote my own!
My purpose was for rendering a number to a screen, hence the function names.
void RenderNumber(int to_print)
{
if (to_print < 0)
{
RenderMinusSign()
RenderNumber(-to_print);
}
else
{
int digits = 1; // Assume if 0 is entered we want to print 0 (i.e. minimum of 1 digit)
int max = 10;
while (to_print >= max) // find how many digits the number is
{
max *= 10;
digits ++;
}
for (int i = 0; i < digits; i++) // loop through each digit
{
max /= 10;
int num = to_print / max; // isolate first digit
to_print -= num * max; // subtract first digit from number
RenderDigit(num);
}
}
}
Based on #Abyx's answer, but uses div so that only 1 division is done per digit.
#include <cstdlib>
#include <iostream>
void print_each_digit(int x)
{
div_t q = div(x, 10);
if (q.quot)
print_each_digit(q.quot);
std::cout << q.rem << '-';
}
int main()
{
print_each_digit(12476);
std::cout << std::endl;
return 0;
}
Output:
1-2-4-7-6-
N.B. Only works for non-negative ints.
My solution:
void getSumDigits(int n) {
std::vector<int> int_to_vec;
while(n>0)
{
int_to_vec.push_back(n%10);
n=n/10;
}
int sum;
for(int i=0;i<int_to_vec.size();i++)
{
sum+=int_to_vec.at(i);
}
std::cout << sum << ' ';
}
The answer I've used is this simple function:
int getDigit(int n, int position) {
return (n%(int)pow(10, position) - (n % (int)pow(10, position-1))) / (int)pow(10, position-1);
}
Hope someone finds this helpful!
// Online C++ compiler to run C++ program online
#include <iostream>
#include <cmath>
int main() {
int iNums = 123458;
// int iNumsSize = 5;
int iNumsSize = trunc(log10(iNums)) + 1; // Find length of int value
for (int i=iNumsSize-1; i>=0; i--) {
int y = pow(10, i);
// The pow() function returns the result of the first argument raised to
the power of the second argument.
int z = iNums/y;
int x2 = iNums / (y * 10);
printf("%d ",z - x2*10 ); // Print Values
}
return 0;
}
You can do it using a while loop and the modulo operators.
It just gives the digits in the revese order.
int main() {
int iNums = 12476;
int iNum = 0;
while(iNums > 0) {
iNum = iNums % 10;
cout << iNum;
iNums = iNums / 10;
}
}
int a;
cout << "Enter a number: ";
cin >> a;
while (a > 0) {
cout << a % 10 << endl;
a = a / 10;
}
int iNums = 12345;
int iNumsSize = 5;
for (int i=iNumsSize-1; i>=0; i--) {
int y = pow(10, i);
int z = iNums/y;
int x2 = iNums / (y * 10);
printf("%d-",z - x2*10 );
}