Sum of digits of N to the power P - c++

My C++ code is supposed to take a number and an exponent as integer inputs, calculate the 'number' to the power of THAT 'exponent' and sum the digits of the result and output it. It works well for small exponent values like 10 or 20, but gives wrong answers for large values like ~ >500. I have limited my 'number' inputs to <5 for wease of computability. I cannot figure out what is wrong with my logic.
#include<iostream>
using namespace std;
#include <cmath>
int main(){
int number, exponent;
cin >> number >> exponent;
double product = 1;
int sum = 0;
// Write your code here
for (int i = 0; i < exponent; i++){
product = product * number;
}
cout << "THE MAIN PRODUCT IS: " << product << "\n\n";
while (product > 1){
sum = sum + fmod(product, 10.0); // kEEP ADDING THE DIGITS TO THE SUM
cout << "sum is " << sum << endl;
product = product / 10.000;
cout << "product is " << product << endl;
}
cout << endl;
cout << sum << endl;
}

The issue with a large exponent is the length of the final answer or the number of digits in the final answer.
In C++, the largest integer that can be represented is 18-19 digits.
If the number exceeds beyond a limit, it will cause an integer overflow.
So, the best way to tackle this problem is to make use of strings or integer arrays.
Have a look at the following implementation:
#include <iostream>
#include <math.h>
// Maximum number of digits in
// output
#define MAX 100000
int multiply(int x, int res[], int res_size) {
// Initialize carry
int carry = 0;
// One by one multiply n with
// individual digits of res[]
for (int i = 0; i < res_size; i++) {
int prod = res[i] * x + carry;
// Store last digit of
// 'prod' in res[]
res[i] = prod % 10;
// Put rest in carry
carry = prod / 10;
}
// Put carry in res and
// increase result size
while (carry) {
res[res_size] = carry % 10;
carry = carry / 10;
res_size++;
}
return res_size;
}
// This function finds
// power of a number x
long long power(int x, int n)
{
//printing value "1" for power = 0
if(n == 0 ){
return 1;
}
int res[MAX];
int res_size = 0;
int temp = x;
// Initialize result
// Representing base in reverse form
while (temp != 0) {
res[res_size++] = temp % 10;
temp = temp / 10;
}
// Multiply x n times
// (x^n = x*x*x....n times)
for (int i = 2; i <= n; i++)
res_size = multiply(x, res, res_size);
long long final_answer = 0;
//Finally taking sum of all the digits in the answer.
for(int i=0;i<res_size; i++){
final_answer += res[i];
}
return final_answer;
}
int main() {
int exponent = 8;
int base = 34;
std::cout<<power(base, exponent);
return 0;
}
Output:
76

Related

Factorial function only returning inputted answer in C++?

I have to create a program which calculates the factorial of any number, the problem is if I input any number above 20 it just returns that number. What in my else if statement could be causing this and is there a better way to solve this? ( this function is called in main and works if num <= 20)
void factorial() {
//User input for number
long long num;
std::cout << "Input any positive integer to find its factorial: ";
std::cin >> num;
unsigned long long numFact = 1;
if (num <= 20) {
while (num > 0) {
numFact = numFact * num;
num = num - 1;
}
std::cout << numFact;
}
else if (num > 20) {
std::vector<int> multFactorial;
//stores num as seperate elements in vector multFactorial
while (num > 0) {
int remain = num % 10;
num = num / 10;
multFactorial.insert(multFactorial.begin(), remain);
}
std::vector<int> answer;
std::vector<int> answerFinal;
//Manually multiplies elements in multFactorial
//Then adds new vectors created by multiplying to get final answer
//Repeats until factorial is solved
//Ex: 21 * 20; 0 * 1 and 0 * 2 stored as {0 , 0}
//2*1 and 2*2 stored as {4, 2, 0}
//Vectors will be addes to get {4, 2, 0} and then that will be multiplied
by 19 until num = 1
while (num > 1) {
for (int i = multFactorial.size() - 1; i >= 0; i--) {
int remain1 = ((num - 1) % 10) * multFactorial[i];
answer.insert(answer.begin(), remain1);
int remain2 = (((num - 1) / 10) * multFactorial[i]);
answerFinal.insert(answerFinal.begin(), remain2);
}
answerFinal.insert(answerFinal.begin(), 0);
//Adds vectors to get final value seperate as digits
for (int i = multFactorial.size() - 1; i >= 0; i--) {
multFactorial[i] = answer[i] + answerFinal[i];
}
num = num - 1;
}
//Prints what should be the factorial of the number input
for (size_t i = 0; i < multFactorial.size(); i++) {
std::cout << multFactorial[i];
}
}
}
Factorials of large numbers results in huge numbers. This can be accommodated in languages like C, C++ etc by putting the results into arbitrary length strings.
Here is an algorithm for that - similar to yours.
https://www.geeksforgeeks.org/factorial-large-number/
Best advice is to check your code against this.
Use a debugger if you have one and step through the code line by line.
If not print out intermediate results and compare with expected.
EDIT: As per review comment, the code at above ref is similar to below- just in case link is broken in future.
// C++ program to compute factorial of big numbers
#include<iostream>
using namespace std;
// Maximum number of digits in output
#define MAX 100 // change to whatever value you need
int multiply(int x, int res[], int res_size);
// Calculate factorial of large number
void factorial(int n)
{
int res[MAX];
// Initialize result
res[0] = 1;
int res_size = 1;
// Apply factorial formula
for (int x=2; x<=n; x++)
res_size = multiply(x, res, res_size);
// print out the result
cout << "Factorial is \n";
for (int i=res_size-1; i>=0; i--)
cout << res[i];
}
// Multiplies x with the number represented by res[].
// res_size is size of res[] or number of digits in the
// number represented by res[].
int multiply(int x, int res[], int res_size)
{
int carry = 0; // Initialize carry
// One by one multiply n with individual digits of res[]
for (int i=0; i<res_size; i++)
{
int prod = res[i] * x + carry;
// Store last digit of 'prod' in res[]
res[i] = prod % 10;
// Put rest in carry
carry = prod/10;
}
// Put carry in res and increase result size
while (carry)
{
res[res_size] = carry%10;
carry = carry/10;
res_size++;
}
return res_size;
}
// Main program
int main()
{
//put code here to read a number
factorial(50); // take 50 for example
return 0;
}

How do I find the smallest number than can be divided by all numbers 1:n with no remainder?

I have been trying to solve problem number 5 on Project Euler which goes like
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
I decided to go a step further and I decided I'd make it find the smallest positive number that is evenly divisible by all of the numbers from 1 to limit where limit is user-defined.
Problem starts when I execute my program, it immediately prints out 0. I tried tracing my code but that didn't work out.
#include <iostream>
using std::cout;
using std::cin;
bool isRemainderFree(int num, int limit){
bool bIsRemainderFree = true;
if(num < limit){
bIsRemainderFree = false;
}else{
for(int i=1; i <= limit; i++){
if(num % i != 0){
bIsRemainderFree = false;
break;
}
}
}
return bIsRemainderFree;
}
int smallestMultiple(int limit){
int smallestNum = 10;
for(int i=1; i <= limit; i++){
bool bFree = isRemainderFree(i, 10);
if(bFree){
cout << i << " is divisible by all numbers from 1 to " << limit << ".\n";
smallestNum = i;
return smallestNum;
break;
}
}
}
int main(){
int limit;
cin >> limit;
int smallestNum = smallestMultiple(limit);
cout << smallestNum;
return 0;
}
The answer should be simply the LCM of all numbers, it can be easily done in the following way
int gcd(int a, int b){
if(b==0)
return a;
return gcd(b, a%b);
}
int main() {
int limit = 10, lcm = 1;
for(int i=1; i<=limit; i++){
lcm = (lcm * i)/gcd(lcm,i);
}
printf("%d\n", lcm); // prints 2520
return 0;
}
PYTHON CODE
import math
# Returns the lcm of first n numbers
def lcm(n):
ans = 1
for i in range(1, n + 1):
ans = int((ans * i)/math.gcd(ans, i))
return ans
# main
n = 20
print (lcm(n))

Efficiently getting all divisors of a given number

According to this post, we can get all divisors of a number through the following codes.
for (int i = 1; i <= num; ++i){
if (num % i == 0)
cout << i << endl;
}
For example, the divisors of number 24 are 1 2 3 4 6 8 12 24.
After searching some related posts, I did not find any good solutions. Is there any efficient way to accomplish this?
My solution:
Find all prime factors of the given number through this solution.
Get all possible combinations of those prime factors.
However, it doesn't seem to be a good one.
Factors are paired. 1 and 24, 2 and 12, 3 and 8, 4 and 6.
An improvement of your algorithm could be to iterate to the square root of num instead of all the way to num, and then calculate the paired factors using num / i.
You should really check till square root of num as sqrt(num) * sqrt(num) = num:
Something on these lines:
int square_root = (int) sqrt(num) + 1;
for (int i = 1; i < square_root; i++) {
if (num % i == 0&&i*i!=num)
cout << i << num/i << endl;
if (num % i == 0&&i*i==num)
cout << i << '\n';
}
There is no efficient way in the sense of algorithmic complexity (an algorithm with polynomial complexity) known in science by now. So iterating until the square root as already suggested is mostly as good as you can be.
Mainly because of this, a large part of the currently used cryptography is based on the assumption that it is very time consuming to compute a prime factorization of any given integer.
Here's my code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
#define pii pair<int, int>
#define MAX 46656
#define LMT 216
#define LEN 4830
#define RNG 100032
unsigned base[MAX / 64], segment[RNG / 64], primes[LEN];
#define sq(x) ((x)*(x))
#define mset(x,v) memset(x,v,sizeof(x))
#define chkC(x,n) (x[n>>6]&(1<<((n>>1)&31)))
#define setC(x,n) (x[n>>6]|=(1<<((n>>1)&31)))
// http://zobayer.blogspot.com/2009/09/segmented-sieve.html
void sieve()
{
unsigned i, j, k;
for (i = 3; i<LMT; i += 2)
if (!chkC(base, i))
for (j = i*i, k = i << 1; j<MAX; j += k)
setC(base, j);
primes[0] = 2;
for (i = 3, j = 1; i<MAX; i += 2)
if (!chkC(base, i))
primes[j++] = i;
}
//http://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/
vector <pii> factors;
void primeFactors(int num)
{
int expo = 0;
for (int i = 0; primes[i] <= sqrt(num); i++)
{
expo = 0;
int prime = primes[i];
while (num % prime == 0){
expo++;
num = num / prime;
}
if (expo>0)
factors.push_back(make_pair(prime, expo));
}
if ( num >= 2)
factors.push_back(make_pair(num, 1));
}
vector <int> divisors;
void setDivisors(int n, int i) {
int j, x, k;
for (j = i; j<factors.size(); j++) {
x = factors[j].first * n;
for (k = 0; k<factors[j].second; k++) {
divisors.push_back(x);
setDivisors(x, j + 1);
x *= factors[j].first;
}
}
}
int main() {
sieve();
int n, x, i;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x;
primeFactors(x);
setDivisors(1, 0);
divisors.push_back(1);
sort(divisors.begin(), divisors.end());
cout << divisors.size() << "\n";
for (int j = 0; j < divisors.size(); j++) {
cout << divisors[j] << " ";
}
cout << "\n";
divisors.clear();
factors.clear();
}
}
The first part, sieve() is used to find the prime numbers and put them in primes[] array. Follow the link to find more about that code (bitwise sieve).
The second part primeFactors(x) takes an integer (x) as input and finds out its prime factors and corresponding exponent, and puts them in vector factors[]. For example, primeFactors(12) will populate factors[] in this way:
factors[0].first=2, factors[0].second=2
factors[1].first=3, factors[1].second=1
as 12 = 2^2 * 3^1
The third part setDivisors() recursively calls itself to calculate all the divisors of x, using the vector factors[] and puts them in vector divisors[].
It can calculate divisors of any number which fits in int. Also it is quite fast.
Plenty of good solutions exist for finding all the prime factors of not too large numbers. I just wanted to point out, that once you have them, no computation is required to get all the factors.
if N = p_1^{a}*p_{2}^{b}*p_{3}^{c}.....
Then the number of factors is clearly (a+1)(b+1)(c+1).... since every factor can occur zero up to a times.
e.g. 12 = 2^2*3^1 so it has 3*2 = 6 factors. 1,2,3,4,6,12
======
I originally thought that you just wanted the number of distinct factors. But the same logic applies. You just iterate over the set of numbers corresponding to the possible combinations of exponents.
so int he example above:
00
01
10
11
20
21
gives you the 6 factors.
If you want all divisors to be printed in sorted order
int i;
for(i=1;i*i<n;i++){ /*print all the divisors from 1(inclusive) to
if(n%i==0){ √n (exclusive) */
cout<<i<<" ";
}
}
for( ;i>=1;i--){ /*print all the divisors from √n(inclusive) to
if(n%i==0){ n (inclusive)*/
cout<<(n/i)<<" ";
}
}
If divisors can be printed in any order
for(int j=1;j*j<=n;j++){
if(n%j==0){
cout<<j<<" ";
if(j!=(n/j))
cout<<(n/j)<<" ";
}
}
Both approaches have complexity O(√n)
Here is the Java Implementation of this approach:
public static int countAllFactors(int num)
{
TreeSet<Integer> tree_set = new TreeSet<Integer>();
for (int i = 1; i * i <= num; i+=1)
{
if (num % i == 0)
{
tree_set.add(i);
tree_set.add(num / i);
}
}
System.out.print(tree_set);
return tree_set.size();
}
//Try this,it can find divisors of verrrrrrrrrry big numbers (pretty efficiently :-))
#include<iostream>
#include<cstdio>
#include<cmath>
#include<vector>
#include<conio.h>
using namespace std;
vector<double> D;
void divs(double N);
double mod(double &n1, double &n2);
void push(double N);
void show();
int main()
{
double N;
cout << "\n Enter number: "; cin >> N;
divs(N); // find and push divisors to D
cout << "\n Divisors of "<<N<<": "; show(); // show contents of D (all divisors of N)
_getch(); // used visual studio, if it isn't supported replace it by "getch();"
return(0);
}
void divs(double N)
{
for (double i = 1; i <= sqrt(N); ++i)
{
if (!mod(N, i)) { push(i); if(i*i!=N) push(N / i); }
}
}
double mod(double &n1, double &n2)
{
return(((n1/n2)-floor(n1/n2))*n2);
}
void push(double N)
{
double s = 1, e = D.size(), m = floor((s + e) / 2);
while (s <= e)
{
if (N==D[m-1]) { return; }
else if (N > D[m-1]) { s = m + 1; }
else { e = m - 1; }
m = floor((s + e) / 2);
}
D.insert(D.begin() + m, N);
}
void show()
{
for (double i = 0; i < D.size(); ++i) cout << D[i] << " ";
}
int result_num;
bool flag;
cout << "Number Divisors\n";
for (int number = 1; number <= 35; number++)
{
flag = false;
cout << setw(3) << number << setw(14);
for (int i = 1; i <= number; i++)
{
result_num = number % i;
if (result_num == 0 && flag == true)
{
cout << "," << i;
}
if (result_num == 0 && flag == false)
{
cout << i;
}
flag = true;
}
cout << endl;
}
cout << "Press enter to continue.....";
cin.ignore();
return 0;
}
for (int i = 1; i*i <= num; ++i)
{
if (num % i == 0)
cout << i << endl;
if (num/i!=i)
cout << num/i << endl;
}
for( int i = 1; i * i <= num; i++ )
{
/* upto sqrt is because every divisor after sqrt
is also found when the number is divided by i.
EXAMPLE like if number is 90 when it is divided by 5
then you can also see that 90/5 = 18
where 18 also divides the number.
But when number is a perfect square
then num / i == i therefore only i is the factor
*/
//DIVISORS IN TIME COMPLEXITY sqrt(n)
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
ll int n;
cin >> n;
for(ll i = 2; i <= sqrt(n); i++)
{
if (n%i==0)
{
if (n/i!=i)
cout << i << endl << n/i<< endl;
else
cout << i << endl;
}
}
}
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define MOD 1000000007
#define fo(i,k,n) for(int i=k;i<=n;++i)
#define endl '\n'
ll etf[1000001];
ll spf[1000001];
void sieve(){
ll i,j;
for(i=0;i<=1000000;i++) {etf[i]=i;spf[i]=i;}
for(i=2;i<=1000000;i++){
if(etf[i]==i){
for(j=i;j<=1000000;j+=i){
etf[j]/=i;
etf[j]*=(i-1);
if(spf[j]==j)spf[j]=i;
}
}
}
}
void primefacto(ll n,vector<pair<ll,ll>>& vec){
ll lastprime = 1,k=0;
while(n>1){
if(lastprime!=spf[n])vec.push_back(make_pair(spf[n],0));
vec[vec.size()-1].second++;
lastprime=spf[n];
n/=spf[n];
}
}
void divisors(vector<pair<ll,ll>>& vec,ll idx,vector<ll>& divs,ll num){
if(idx==vec.size()){
divs.push_back(num);
return;
}
for(ll i=0;i<=vec[idx].second;i++){
divisors(vec,idx+1,divs,num*pow(vec[idx].first,i));
}
}
void solve(){
ll n;
cin>>n;
vector<pair<ll,ll>> vec;
primefacto(n,vec);
vector<ll> divs;
divisors(vec,0,divs,1);
for(auto it=divs.begin();it!=divs.end();it++){
cout<<*it<<endl;
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
sieve();
ll t;cin>>t;
while(t--) solve();
return 0;
}
We can use modified sieve for getting all the factors for all numbers in range [1, N-1].
for (int i = 1; i < N; i++) {
for (int j = i; j < N; j += i) {
ans[j].push_back(i);
}
}
The time complexity is O(N * log(N)) as the sum of harmonic series 1 + 1/2 + 1/3 + ... + 1/N can be approximated to log(N).
More info about time complexity : https://math.stackexchange.com/a/3367064
P.S : Usually in programming problems, the task will include several queries where each query represents a different number and hence precalculating the divisors for all numbers in a range at once would be beneficial as the lookup takes O(1) time in that case.
java 8 recursive (works on HackerRank). This method includes option to sum and return the factors as an integer.
static class Calculator implements AdvancedArithmetic {
public int divisorSum(int n) {
if (n == 1)
return 1;
Set<Integer> set = new HashSet<>();
return divisorSum( n, set, 1);
}
private int divisorSum(int n, Set<Integer> sum, int start){
if ( start > n/2 )
return 0;
if (n%start == 0)
sum.add(start);
start++;
divisorSum(n, sum, start);
int total = 0;
for(int number: sum)
total+=number;
return total +n;
}
}

No repeating digits and reconstructing int

The program i am designing is for an assignment, but as a do distant learning it is not easy finding a solution.
The program that I have to create must first ask user for an unsigned long int and then break that number down to each digit without repeating number (for example 3344 the program should list 3 and 4), my program just lists all digits. After they have been listed the position of that digits needs to be dispayed with the position (digit at the right is position 0). Then the program should be "reconstruct" to make the original unsigned long int.
An example of what it should look like :
7377683
3 : 0 5
6 : 2
7 : 3 4 6
8 : 1
7377683
The code that i am using currently :
#include <iostream>
using namespace std;
int main()
{
unsigned long int number;
cout << "Enter an integer " << endl;
cin >> number;
for(int i=0; i<10 ; i++)
{
if (number > 0)
{
cout << number%10 << " : " << i; //output digit and position
cout << "\n";
number /= 10;
}
}
return 0;
}
I cannot use arrays or strings to complete this task and that is what i am finding challenging.
You could store digit positions in a decimal bitmask type thing.
unsigned long n, digits[10]{};
// Input
std::cin >> n;
// Break down
for (int i = 1; n; i *= 10, n /= 10)
digits[n % 10] += i;
// Reconstruct and print digit positions
for (int i = 0; i < 10; i++) {
if (!digits[i])
continue;
n += digits[i] * i;
std::cout << i << ":";
for (int j = 0; digits[i]; j++, digits[i] /= 10)
if (digits[i] % 10)
std::cout << " " << j;
std::cout << std::endl;
}
// Output
std::cout << n;
It's kinda neat because you don't need to know how many digits your number has. Also, you could construct the new number and output the positions of all digits in the same loop which you are breaking it down, thus removing the need to store the digits anywhere, but that feels like cheating.
Since you can't use arrays or strings you can probably get away with using an integral type as a bitmap. Any time you output a number in your loop set a bit in the bitmap that corresponds to that number. Then when you need to output that number you check to see if that bit is set and if it is you skip printing it out. Something like the following maybe.
for (int mask = 0, i = 0; i<10; i++)
{
if (number > 0)
{
int value = number % 10;
if ((mask & (1 << value)) == 0)
{
cout << value << " : " << i << endl; //output digit and position
mask |= 1 << value;
}
number /= 10;
}
}
Taking a number down into individual digits works like this:
int number = 4711;
vector<int> v;
while(number > 0)
{
int digit = number % 10;
number /= 10;
v.push_back(digit);
}
Putting it back together again into an integer (we need to go "backwards", as the digits come out "back to front" in the above code)
int number = 0;
for(int i = v.size()-1; i >= 0; i--)
{
number *= 10;
number += v[i];
}
I'm intentionally not showing a complete program to solve your problem, since part of learning programming is to learn how to solve problems. But you sometimes need a few "steps" on the way.
Something like this would solve it with arrays:
int array[10][10] = { { 0 } }; // Position of each digit.
int count[10] = { 0 }; // Number of each digit
int number = 4711;
int pos = 0;
while(number > 0)
{
int digit = number % 10;
number /= 10;
count[digit]++;
array[digit][count[digit]] = pos;
pos++;
}
I'm leaving it to you to fill in the rest of the code (to print and reassemble the number). [The above code doesn't cope with the number zero].
This is the working solution which address to the most crucial problem in your question:
int number = 7377683;
int temp = number;
int pos = 0;
int counter = 0;
int currNum;
int uniqueCount = 0;
Added: Codes to check number of unique digits in number:
for (int x=0; x<9; x++)
for (int y=temp; y>0; y/=10)
if (y%10 == x)
{
uniqueCount ++;
break;
}
Codes to generate the output of every unique elements and positions:
for (int y=0; y<uniqueCount; y++)
{
pos = counter;
currNum = number%10;
cout << temp%10 << " : ";
for (int x=temp; x>0; x/=10)
{
if (temp%10 == currNum)
cout << pos << " ";
pos++;
temp /= 10;
}
counter++;
number /=10;
temp = number;
cout << endl << endl;
}
Program Output:
3 : 0 5
8 : 1
6 : 2
7 : 3 4 6
This solution is using the most basic construct without array (according to your requirements).

C decimal to binary without arrays

I think I've almost got it, but I feel like I'm go in circles trying to figure this out.
The challenge to out cout without using strings or arrays. I took the number 56 as an example and 56 should equal 111000 this is not the case as it goes through fine till 7 then the number equals number*2 + number%2 makes it equal to 15 and outputs all 1's. Idk anymore, this is driving me to the moon and back.
#include <iostream>
using namespace std;
int main()
{
int number = 0;
int n = 1;
int x = n;
cin>>number;
cout<<n%2;
while(n <= number)
{
if(n%2 == 0)
{
n = n*2;
cout<<0;
}
else
{
n = n*2 + n%2;
cout<<n%2;
}
}
}
You can use the binary operator & to check if a single bit is 1 or 0.
for (int i=512; i>0; i/=2) {
cout << ( ( number & i ) != 0 ) ;
}
Note that this WILL print leading 0's.
Also, I'm assuming you only want to print positive integers.
Alternative:
for (int i=512; i>0; i/=2) {
if (number >= i) {
cout << 1;
number -= i;
} else {
count << 0;
}
}
You can use recursion
void decimal_to_binary(int decimal)
{
int remainder = decimal % 2;
if (decimal < 1)
return;
decimal_to_binary(decimal / 2);
cout << remainder;
}
This function will take the decimal, get its remainder when divided to 2. Before it the function call itself again, it checks if the decimal is less than 1(probably 0) and return to execute the printing of 1's and 0's
I had this type of problem assigned to me recently. This code example work up to a maximum of 10 binary digits (per the problem guidelines) and keep prompting for input until 0 is entered (sentinel value). This can certainly be improved but the math is correct:
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
//Declare Variables
int inputValue = 0;
int workingValue = 0;
int conversionSum = 0;
//Begin Loop
do{
//Prompt for input
cout << "Enter a binary integer (0 to quit): ";
cin >> inputValue;
//Reset Variables
workingValue = inputValue;
conversionSum = 0;
//Begin processing input
//10 digits max, so 10 iterations
for (int i=0; i<10; i++) {
//Check for non-binary entry
if ((workingValue % 10) != 1 && (workingValue % 10 != 0)){
cout << "Invalid!\n";
workingValue = 0;
conversionSum = 0;
break;
}
//check to see if 2^i should be added to sum
if (workingValue%2 == 1){
conversionSum += pow(2,i);
workingValue--;
}
//divide by 10 and continue loop
workingValue= workingValue / 10;
}
//output results
cout << "converted to decimal is: " << conversionSum << endl;
}while (inputValue != 0);
}
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
cout << "enter a number";
int number, n, a=0;
cin >> number;
n = number;
do
{
n=n/2;
a=a+1;
}
while (n>=1);
cout << "a is" << a;
int c = a;
int b = a;
cout << "binary is";
for(int i=0; i<=c; i++)
{
int k = number / pow(2,b);
cout << k;
number = number - k * pow(2,b);
b = b-1;
}
return 0;
}
Although asked in C I have used C++. I have used the logic that if you have to convert decimal to binary we have to find the maximum power of 2 contained in the number which when added by 1 becomes the number of digit of required binary .. leftmost digit is the number of highest available power of 2 (ex in 8 highest power of 2 is 3 and 1 such is available)...then subtract this from the number and (ex 8-8=0)and search for number of next highest available power of 2 and so on.