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;
}
Related
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"
}
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.
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";
}
}
#include <iostream>
using namespace std;
void whosprime(long long x)
{
bool imPrime = true;
for(int i = 1; i <= x; i++)
{
for(int z = 2; z <= x; z++)
{
if((i != z) && (i%z == 0))
{
imPrime = false;
break;
}
}
if(imPrime && x%i == 0)
cout << i << endl;
imPrime = true;
}
}
int main()
{
long long r = 600851475143LL;
whosprime(r);
}
I'm trying to find the prime factors of the number 600851475143 specified by Problem 3 on Project Euler (it asks for the highest prime factor, but I want to find all of them). However, when I try to run this program I don't get any results. Does it have to do with how long my program is taking for such a large number, or even with the number itself?
Also, what are some more efficient methods to solve this problem, and do you have any tips as to how can I steer towards these more elegant solutions as I'm working a problem out?
As always, thank you!
Your algorithm is wrong; you don't need i. Here's pseudocode for integer factorization by trial division:
define factors(n)
z = 2
while (z * z <= n)
if (n % z == 0)
output z
n /= z
else
z++
if n > 1
output n
I'll leave it to you to translate to C++ with the appropriate integer datatypes.
Edit: Fixed comparison (thanks, Harold) and added discussion for Bob John:
The easiest way to understand this is by an example. Consider the factorization of n = 13195. Initially z = 2, but dividing 13195 by 2 leaves a remainder of 1, so the else clause sets z = 3 and we loop. Now n is not divisible by 3, or by 4, but when z = 5 the remainder when dividing 13195 by 5 is zero, so output 5 and divide 13195 by 5 so n = 2639 and z = 5 is unchanged. Now the new n = 2639 is not divisible by 5 or 6, but is divisible by 7, so output 7 and set n = 2639 / 7 = 377. Now we continue with z = 7, and that leaves a remainder, as does division by 8, and 9, and 10, and 11, and 12, but 377 / 13 = 29 with no remainder, so output 13 and set n = 29. At this point z = 13, and z * z = 169, which is larger than 29, so 29 is prime and is the final factor of 13195, so output 29. The complete factorization is 5 * 7 * 13 * 29 = 13195.
There are better algorithms for factoring integers using trial division, and even more powerful algorithms for factoring integers that use techniques other than trial division, but the algorithm shown above will get you started, and is sufficient for Project Euler #3. When you're ready for more, look here.
A C++ implementation using #user448810's pseudocode:
#include <iostream>
using namespace std;
void factors(long long n) {
long long z = 2;
while (z * z <= n) {
if (n % z == 0) {
cout << z << endl;
n /= z;
} else {
z++;
}
}
if (n > 1) {
cout << n << endl;
}
}
int main(int argc, char *argv[]) {
long long r = atoll(argv[1]);
factors(r);
}
// g++ factors.cpp -o factors ; factors 600851475143
Perl implementation with the same algorithm is below.
Runs ~10-15x slower (Perl 0.01 seconds for n=600851475143)
#!/usr/bin/perl
use warnings;
use strict;
sub factors {
my $n = shift;
my $z = 2;
while ($z * $z <= $n) {
if ( $n % $z ) {
$z++;
} else {
print "$z\n";
$n /= $z;
}
}
if ( $n > 1 ) {
print "$n\n"
}
}
factors(shift);
# factors 600851475143
600851475143 is outside of the range of an int
void whosprime(int x) //<-----fix heere ok?
{
bool imPrime = true;
for(int i = 1; i <= x; i++)
{...
...
Try below code:
counter = sqrt(n)
i = 2;
while (i <= counter)
if (n % i == 0)
output i
else
i++
Edit: I'm wrong (see comments). I would have deleted, but the way in which I'm wrong has helped indicate what specifically in the program takes so long to produce output, so I'll leave it :-)
This program should immediately print 1 (I'm not going to enter a debate whether that's prime or not, it's just what your program does). So if you're seeing nothing then the problem isn't execution speed, there muse be some issue with the way you're running the program.
Here is my code that worked pretty well to find the largest prime factor of any number:
#include <iostream>
using namespace std;
// --> is_prime <--
// Determines if the integer accepted is prime or not
bool is_prime(int n){
int i,count=0;
if(n==1 || n==2)
return true;
if(n%2==0)
return false;
for(i=1;i<=n;i++){
if(n%i==0)
count++;
}
if(count==2)
return true;
else
return false;
}
// --> nextPrime <--
// Finds and returns the next prime number
int nextPrime(int prime){
bool a = false;
while (a == false){
prime++;
if (is_prime(prime))
a = true;
}
return prime;
}
// ----- M A I N ------
int main(){
int value = 13195;
int prime = 2;
bool done = false;
while (done == false){
if (value%prime == 0){
value = value/prime;
if (is_prime(value)){
done = true;
}
} else {
prime = nextPrime(prime);
}
}
cout << "Largest prime factor: " << value << endl;
}
Keep in mind that if you want to find the largest prime factor of extremely large number, you have to use 'long' variable type instead of 'int' and tweak the algorithm to process faster.
short and clear vesion:
int main()
{
int MAX = 13195;
for (int i = 2; i <= MAX; i++)
{
while (MAX % i == 0)
{
MAX /= i;
cout << i << ", " << flush; // display only prime factors
}
return 0;
}
This is one of the easiest and simple-to-understand solutions of your question.
It might not be efficient like other solutions provided above but yes for those who are the beginner like me.
int main() {
int num = 0;
cout <<"Enter number\n";
cin >> num;
int fac = 2;
while (num > 1) {
if (num % fac == 0) {
cout << fac<<endl;
num=num / fac;
}
else fac++;
}
return 0;
}
# include <stdio.h>
# include <math.h>
void primeFactors(int n)
{
while (n%2 == 0)
{
printf("%d ", 2);
n = n/2;
}
for (int i = 3; i <= sqrt(n); i = i+2)
{
while (n%i == 0)
{
printf("%d ", i);
n = n/i;
}
}
if (n > 2)
printf ("%d ", n);
}
int main()
{
int n = 315;
primeFactors(n);
return 0;
}
Simple way :
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll largeFactor(ll n)
{
ll ma=0;
for(ll i=2; i*i<=n; i++)
{
while(n%i == 0)
{
n=n/i;
ma=i;
}
}
ma = max(ma, n);
return ma;
}
int main()
{
ll n;
cin>>n;
cout<<largeFactor(n)<<endl;
return 0;
}
Implementation using prime sieve ideone.
Since 600851475143 is out of scope for int as well as single long type wont work here hence here to solve we have to define our own type here with the help of typedef.
Now the range of ll is some what around 9,223,372,036,854,775,807.
typedef long long int LL
Try this code. Absolutely it's the best and the most efficient:
long long number;
bool isRepetitive;
for (int i = 2; i <= number; i++) {
isRepetitive = false;
while (number % i == 0) {
if(!isRepetitive){
cout << i << endl;
isRepetitive = true;
}
number /= i;
}
}
Enjoy! ☻
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 );
}