How do I extract missing digits from an integer? - c++

I'm trying to get the following output:
Enter integer: 87240
Missing digits: 1 3 5 6 9
Here is my code so far:
// Extract numbers inside integer n
while (numOfDigits > 0)
{
int digit = n % 10;
int missing = 0;
while ((digit != missing) && (missing < 10))
{
cout << missing << " ";
missing++;
}
numOfDigits--;
n /= 10;
}
which prints out
Enter integer: 87240
Missing digits: 0 1 2 3 0 1 0 1 2 3 4 5 6 0 1 2 3 4 5 6 7
Is there any way to go about doing this without using an array?

Here is an implementation that uses a single integer (acc) to remember which digits had been seen:
#include <iostream>
using uuint = unsigned long long int;
uuint p(uuint n) { ++n; return n * n - n + 41; }
void print_missing(uuint n)
{
std::cout << "Number " << n << " is missing the following digits:";
uuint acc = 1;
while (n)
{
uuint q = p(n % 10);
if (acc % q != 0) acc *= q;
n /= 10;
}
for (int i = 0; i != 10; ++i)
{
if (acc % p(i) != 0) std::cout << " " << i;
}
std::cout << "\n";
}
int main()
{
for (uuint n; std::cin >> n; )
print_missing(n);
}

You can use a for loop, no need for an array:
#include <string>
#include <iostream>
#include <cstdlib>
int main()
{
std::string integer;
std::cout << "Enter integer: ";
std::getline(std::cin, integer);
for (unsigned int i = 0; i < 10; ++i)
{
const char c = '0' + i;
if (integer.find(c) == std::string::npos)
{
cout << i << " ";
}
}
return EXIT_SUCCESS;
}
The above version keeps the number in text form, easier to search for digits.
You could use a nested loop to check every digit of the number.

Are you interested in using a string instead of an array, perchance? Those are more or less the same idea, but given the input string n we could find any unused digits like this:
const auto digits = "0123456789"s;
sort(begin(n), end(n));
set_difference(cbegin(n), cend(n), cbegin(digits), cend(digits), ostream_iterator<char>(cout, " "));
Live Example

Here the version using a single integer to accumulate the results (still, technically array of bits):
#include <iostream>
#include <cmath>
void check(int n)
{
unsigned short bits = 0;
while (n) {
bits |= 1 << std::abs(n % 10);
n /= 10;
}
std::cout << "Missing digits:";
for (unsigned i = 0; i != 10; ++i) {
if (((bits >> i) & 1) == 0)
std::cout << " " << i;
}
std::cout << std::endl;
}
int main()
{
int n;
std::cout << "Enter a number: ";
std::cin >> n;
check(n);
return 0;
}

No Arrays in this one.
#include <stdio.h>
int NumHasDigit(int num, int digit)
{
while (num)
{
if (num%10 == digit)
{
return 1;
}
num /= 10;
}
return 0;
}
int main(void) {
int x;
printf("Enter int: ");
scanf("%d\n", &x);
printf("Missing Digits:\n");
for(int i=0; i<10; ++i)
{
if (!NumHasDigit(x,i)) printf("%d ", i);
}
return 0;
}
Sample Input:
34567
Sample Output:
Missing Digits
0 1 2 8 9

Related

Extra "0" in output when factorizing a number

Write a function int fact(int n) which displays the factors of the integer n, and returns the number of factors. Call this function in main() with user input
#include<iostream>
using namespace std;
int fact(int n);
int main() {
int n,factor;
cout << "Enter an integer : ";
cin >> n;
factor = fact(n);
cout << factor;
return 0;
}
int fact(int n)
{
for (int i = 1; i <= n; ++i)
{
if (n % i == 0)
cout << i << endl;
}
return 0;
}
If I enter 7, I get 1,7,0 . How do i remove this 0 and how do i find the number of factors?
You should count in your int fact() function. Set a variable to 0 and increment each time you currently display i. Then at the end of the function instead of returning 0 return the count variable.
int fact(int n)
{
int count=0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0) {
cout << i << endl;
count++;
}
}
return count;
}
The key part is "and returns the number of factors". You don't do that. Keep a count of the factors:
int fact(int n)
{
int count = 0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0)
{
// found a factor, add to the count
count++;
cout << i << endl;
}
}
// return the count instead
return count;
}
Then, your main function can use that count:
factor = fact(n); // fact(n) will already print the factors
// now just print the number
cout << "Number of factors: " << factor << '\n';
#include <iostream>
#include <vector>
std::vector<int> fact(int n);
int main() {
int n;
std::cout << "Number: ";
std::cin >> n;
std::vector<int> factors = fact(n);
for (auto i : factors) {
std::cout << i << ' ';
}
std::cout << '\n';
std::cout << "Number of factors: " << factors.size() << '\n';
return 0;
}
std::vector<int> fact(int n) {
std::vector<int> vec{1};
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
vec.push_back(i);
}
}
vec.push_back(n);
return vec;
}
If you're going to return anything from fact(), it should be the factors. To do so, I am using a std::vector. It is an array that can grow on demand. The numbers 1 and n are always factors, so I don't bother doing the math for them. The vector is initialized already holding the value 1, and I only calculate numbers up to and including half of n (Anything greater than n/2 won't divide evenly, so my loop is finished about half as fast by recognizing the actual range). I then just add n to the vector, which I return.
My main prints the vector, and the vector knows its own size, which is the number of factors.
Alternatively, you can just keep a count in your fact() function.
#include <iostream>
#include <vector>
// Prints factors of n and returns the number of factors
int fact(int n);
int main() {
int n;
std::cout << "Number: ";
std::cin >> n;
int numFactors = fact(n);
std::cout << "Number of factors: " << numFactors << '\n';
return 0;
}
int fact(int n) {
int factorCount = 2; // Already counting 1 and n
std::cout << "1 ";
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
std::cout << i << ' ';
++factorCount;
}
}
std::cout << n << '\n';
return factorCount;
}
The main problem with your code is that your function always returns zero. You need to keep a count of factors and return it.
Besides that your code performance badly as the loop goes on much longer than needed. You can use the square root of n as the limit in the for loop. Like:
int fact(int n)
{
if (n < 1) return 0;
int res = 0;
int limit = sqrt(n);
for (int i = 1; i <= limit; ++i)
{
if (n % i == 0)
{
res += 2;
cout << i << " - " << n/i << endl;
}
}
if (limit * limit == n)
{
--res;
}
return res;
}
For n = 36 the output is:
1 - 36
2 - 18
3 - 12
4 - 9
6 - 6
and the returned value is 9
Below is another approach. It doesn't use square root. Instead it keeps the number of loops low by using the square of i as loop limit.
int fact(int n)
{
if (n < 1) return 0;
int res = 0;
int i = 1;
int i_square = i * i;
while (i_square < n)
{
if (n % i == 0)
{
res += 2;
cout << i << " - " << n/i << endl;
}
++i;
i_square = i * i;
}
if (i_square == n)
{
++res;
cout << i << " - " << n/i << endl;
}
return res;
}
Fact() always returns 0 so this line print 0
cout << factor;
for the number of factors you can change the return value of fact() :
int fact(int n)
{
int nb = 0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0) {
cout << i << endl;
nb++;
}
}
return nb;
}

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.

c++ how to print 1-10 after that if i input one of them the number will be dissapear

how to print 1-10 after that if i input one of them the number will be disappear.
ex:
Output: 1 2 3 4 5 6 7 8 9 10
Input:1
Output:2 3 4 5 6 7 8 9 10
Input:5
Output:2 3 4 6 7 8 9 10
(only using while or do-while or for)->(not using array)
//let's say that the variable x contains the inputted number, 5 in this case
for (int i = 1; i <= 10; i++){
if (i != x)
printf("%d ", i);
}
The output will be:
1 2 3 4 6 7 8 9 10
#include <bitset>
#include <iostream>
...
constexpr int N = 10;
std::bitset<N+1> mask {-1ul};
while (true) {
int inp;
cin >> inp;
if (inp < 1 || inp > N)
continue;
mask.reset(inp);
for (int i = 1; i < N; ++i) {
if (mask.test(i)) {
std::cout << i << '\n';
}
}
}
I have tested this code on VS2017. I believe you will get an idea of how to do it. Of course, you can improve the efficiency of the source code.
#include "stdafx.h"
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
constexpr int iBitNum = 10;
std::bitset<iBitNum + 1> mask;
mask.set();
int _size = mask.count();
for (int i = 0; i < _size; ++i)
{
mask[i] = 0;
}
int inp = 0;
int b = 0;
while (true)
{
cout << "Enter the number which you do not want to display" << endl;
cin >> inp;
cout << "Here is the result" << endl;
for (size_t i = 0; i < iBitNum; i++)
{
if (i+1==inp)
{
continue;
}
b = mask[i] | i+1;
cout << b << " ";
}
cout << endl;
}
return 0;
}

How do I print the following pattern using 3 for loops instead of 4?

I'm trying to print the following pattern:
*
**
***
****
*****
****
***
**
*
Now, I know how to do it using 4 for loops:
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
cout<<"*";
}
cout<<"\n";
}
to print the first half and to print the second half:
for(i=1;i<=n;i++)
{
for(j=n;j>i;j--)
{
cout<<"*";
}
cout<<"\n";
}
Looking closely, both the outer for loops are the same. i.e.,
for(i=1;i<=n;i++).
Is there anyway to nest both the 'j' for-loops inside the i-for loop?
Using only one loop:
#include <iostream>
#include <string>
int main() {
for (unsigned i = 0; i < 10; ++i)
std::cout << std::string( i < 5 ? (i+1) : 10 - (i+1), '*') << std::endl;
return 0;
}
Would you care for not even three loops, but just two loops?
int n=5, i, j, k;
for (i=0; i<n*2-1; i++)
{
j=i;
if (j >= n)
j=n*2-2-j;
for (k=0; k<=j; k++)
std::cout << '*';
std::cout << std::endl;
}
using 2 loops:
int g=1;
for(int i=0;i<=5;i++){
for (int y=0;y<=i;y+=g){
cout<<"*";
}
cout<<endl;
if (i==4 && g==1){
cout<<"*****";
i=3;
g=-1;
}}
Instead of printing 5 lines, and then another 5, you could print 10, and calculate the number of stars in each line.
for(i = 1; i <= 2*n - 1; i++)
{
for(j = 1; j <= n - abs(i - n); j++)
{
cout<<"*";
}
cout<<"\n";
}
The expression n-abs(i-n) evaluates to i for values of i between 1 and n, and to 2n-i for values of i greater than n.
Just for fun, how about one loop:
for (int i=1, j=0, dir=1; i!=0;) {
cout << '*';
++j;
if (j==i) {
cout << '\n';
j = 0;
i += dir;
if (i==6) {
dir = -1;
i -= 2;
}
}
}
You can do it in one loop (maybe cheating a little bit):
size_t max = 5;
size_t rows = max * 2 - 1;
std::string line(std::string(max, '*') + '\n');
for ( size_t j = 0, k = max; j < rows; ++j ) {
std::cout << line.c_str() + ( j < max ? --k : ++k );
}
I know you didn't ask for it, but for completeness here's one with zero loops (recursion instead):
#include <iostream>
void print_stars(int count)
{
if (count > 0)
{
std::cout << '*';
print_stars(count - 1);
}
}
void print_line(int lines, int stars)
{
if (lines == 1)
print_stars(stars);
else
{
if (stars > 0)
{
print_stars(stars);
std::cout << std::endl;
}
print_line(lines - 1, stars + 1);
std::cout << std::endl;
if (stars > 0)
print_stars(stars);
}
}
int main()
{
int star_count = 5;
print_line(star_count + 1, 0);
return 0;
}
The pattern can be outputted using only one for loop.
Here is a demonstrative program.
#include <iostream>
#include <iomanip>
int main()
{
while ( true )
{
const char c = '*';
std::cout << "Enter non-negative number (0 - exit): ";
unsigned int n;
if ( !( std::cin >> n ) || n == 0 ) break;
std::cout << '\n';
for ( unsigned int i = 1; i < 2 * n; i++ )
{
unsigned int w = i <= n ? i : 2 * n - i;
std::cout << std::setfill( c ) << std::setw( w + 1 ) << '\n';
}
std::cout << std::endl;
}
return 0;
}
If to enter sequentially
5 4 3 2 1 0
then the program output will look the following way
Enter non-negative number (0 - exit): 5
*
**
***
****
*****
****
***
**
*
Enter non-negative number (0 - exit): 4
*
**
***
****
***
**
*
Enter non-negative number (0 - exit): 3
*
**
***
**
*
Enter non-negative number (0 - exit): 2
*
**
*
Enter non-negative number (0 - exit): 1
*
Enter non-negative number (0 - exit): 0
Using the same variables of this well-structured program as function parameters you can write a separate function that outputs the pattern.
Here you are.
#include <iostream>
#include <iomanip>
std::ostream & pattern( unsigned int n, char c = '*', std::ostream &os = std::cout )
{
for ( unsigned int i = 1; i < 2 * n; i++ )
{
unsigned int w = i <= n ? i : 2 * n - i;
os << std::setfill( c ) << std::setw( w + 1 ) << '\n';
}
return os;
}
int main()
{
while ( true )
{
std::cout << "Enter non-negative number (0 - exit): ";
unsigned int n;
if ( !( std::cin >> n ) || n == 0 ) break;
std::cout << '\n';
pattern( n );
std::cout << std::endl;
}
return 0;
}
Take into account that for example it is a bad idea to use the standard class std::string to output the pattern because the program will be inefficient due to allocation and reallocation of the dynamic memory for an object of the class.
If not to use the standard stream manipulators then you can use standard algorithm std::fill_n to hide the inner loop. In this case the program also will have only one explicit loop.
For example
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
while ( true )
{
const char c = '*';
std::cout << "Enter non-negative number (0 - exit): ";
unsigned int n;
if ( !( std::cin >> n ) || n == 0 ) break;
std::cout << '\n';
for ( unsigned int i = 1; i < 2 * n; i++ )
{
unsigned int w = i <= n ? i : 2 * n - i;
*std::fill_n( std::ostream_iterator<char>( std::cout ), w, c ) = '\n';
}
std::cout << std::endl;
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int i;
int j;
int count = 1;
for(i= 0;i<10;i++) {
if(i < 5) {
for(j=0;j<=i;j++) {
cout<<"*";
}
} else {
for(j=i-count;j>0;j--) {
cout<<"*";
}
count +=2;
}
cout<< "\n";
}
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 );
}