I want to create an application that generates full list of phone numbers that satisfies equatation:
x is a rational number.
We can assume that
Now, after some transformations, we obtain
As telephone number is integer and 10^9 is integer, we know that t * 666333999 / s is integer. Therefore s is a divisor of t * 666333999
As yet, my programm searches for all divisors of 666333999. I thing it ought do it well (it should write most of the phone numbers). Unfortunately sometimes my phone number (it's the tym variable) is a negative number.
Why is it so?
Here's my code.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector < unsigned > divisor;
const int number = 666333999;
long double tym; // it's the phone number (9 digits)
for (int i = 2; i < number + 1; i++)
{ // I'm pushing all the divisors to vector.
if (number % i == 0)
{
divisor.push_back(i);
}
}
for(unsigned i = 1; i < divisor.size() + 1; i++)
{ // i are consecutives values of s
for(unsigned j = 1; j < (unsigned)2000000000; j++)
{ // j are consecutives values of t
tym = number / divisor[i];
tym *= j;
if(tym > 99999999 && tym < 2000000000) // I must substract 10^9
{
cout << "\t(!)\t i = " << i << " and j = " << j << ","
"div[i] = " << divisor[i] << ", telephone"
" number = " << (tym - 1000000000) << endl;
}
else if(tym >= 2000000000)
{
break;
}
}
}
}
The number involved in your calculation exceed the capability of a 32 bit integer but may fit the 64 bit integers.
May be in your platform int is 32 bit. Just use long long.
If you want to be sure about the 64 bit, use std::int64_t, defined in <cstdint>
Related
Okay so I'm tryna create a program that:
(1) swaps my array
(2) performs caesar cipher substitution on the swapped array
(3) convert the array from (2) that is in decimal form into 8-bit binary form
And so far I've successfully done the first 2 parts but I'm facing problem with converting the array from decimal to binary form.
And this is my coding of what I've tried
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
void swapfrontback(int a[], int n);
int main()
{
int a[10], i, n;
cout << "enter size" << endl;
cin >> n;
if (n == 0)
{
cout << "Array is empty!\n";
}
else
{
cout << "p = " << endl;
for (i = 0; i < n; i++)
{
cin >> a[i];
}
}
swapfrontback(a,n);
//caesar cipher
int shift = 0;
cout << "input shift: ";
cin >> shift;
int modulus = 0;
cout << "input modulus: ";
cin >> modulus;
cout << "p''=" << endl;
for (i = 0; i < n; i++)
{
a[i] = (a[i] + shift) % modulus;
cout << a[i] << endl;
}
// Function that convert Decimal to binary
int b;
b = 8;
cout<< "p'''=" << endl;
for (i = 0; i < n; i++)
{
for(int i=b-1;i>=0;i--)
{
if( a[i] & ( 1 << i ) ) cout<<1;
else cout<<0;
}
}
return 0;
}
void swapfrontback(int a[], int n)
{
int i, temp;
for (i = 0; i < n / 2; i++)
{
temp = a[i];
a[i] = a[n - i-1];
a[n - i-1] = temp;
}
cout << "p' = '" << endl;
for (i = 0; i < n; i++)
{
cout << a[i] << endl;
}
}
the problem is that instead of converting the array of decimal from the 2nd part which is the caesar cipher into its binary form, I'm getting 000000010000000100000001 .
My initial array is
3
18
25
Shift 8 and modulo 26. If anyone knows how to fix this please do help me.
Well, there seems to be something that may be an issue in the future (like the n being larger than 10, but, regarding your question, this nested for sentence is wrong.
for (i = 0; i < n; i++)
{
for(int i=b-1;i>=0;i--) //here you are using the variable 'i' twice
{
if( a[i] & ( 1 << i ) ) cout<<1; //i starts at 7, which binary representation in 4 bits is 0111
else cout<<0;
}
}
When you're using nested for sentences, it is a good idea to not repeat their iterating variables' names since they can affect each other and create nasty things like infinite loops or something like that. Try to use a different variable name instead to avoid confusion and issues:
for(int j=b-1;j>=0;j--) //this is an example
Finally, the idea behind transforming a base 10 number to its binary representation (is to use the & operator with the number 1 to know if a given bit position is a 1 (true) or 0 (false)) for example, imagine that you want to convert 14 to its binary form (00001110), the idea is to start making the & operation with the number 1, an continue with powers of 2 (since them will always be a number with a single 1 and trailing 0s) 1-1 2-10 4-100 8-1000, etc.
So you start with j = 1 and you apply the & operation between it and your number (14 in this case) so: 00000001 & 00001110 is 0 because there is not a given index in which both numbers have a '1' bit in common, so the first bit of 14 is 0, then you either multiply j by two (j*=2), or shift their bits to the left once (j = 1<<j) to move your bit one position to the left, now j = 2 (00000010), and 2 & 14 is 2 because they both have the second bit at '1', so, since the result is not 0, we know that the second bit of 14 is '1', the algorithm is something like:
int j = 128; 128 because this is the number with a '1' in the 8th bit (your 8 bit limit)
int mynumber = 14;
while(j){ // when the j value is 0, it will be the same as false
if(mynumber & j) cout<<1;
else cout<<0;
j=j>>1;
}
Hope you understand, please ensure that your numbers fit in 8 bits (255 max).
So im working on a class assignment where I need to take a base 2 binary number and convert it to its base 10 equivalent. I wanted to store the binary as a string, then scan the string and skip the 0s, and at 1s add 2^i. Im not able to compare the string at index i to '0, and im not sure why if(binaryNumber.at(i) == '0') isnt working. It results in an "out of range memory error". Can someone help me understand why this doesnt work?
#include <iostream>
using namespace std;
void main() {
string binaryNumber;
int adder;
int total = 0;
cout << "Enter a binary number to convert to decimal \n";
cin >> binaryNumber;
reverse(binaryNumber.begin(),binaryNumber.end());
for (int i = 1; i <= binaryNumber.length(); i++) {
if(binaryNumber.at(i) == '0') { //THIS IS THE PROBLEM
//do nothing and skip to next number
}
else {
adder = pow(2, i);
total = adder + total;
}
}
cout << "The binary number " << binaryNumber << " is " << total << " in decimal form.\n";
system("pause");
}
Array indices for C++ and many other languages use zero based index. That means for array of size 5, index ranges from 0 to 4. In your code your are iterating from 1 to array_length. Use:
for (int i = 0; i < binaryNumber.length(); i++)
The problem is not with the if statement but with your loop condition and index.
You have your index begin at one, while the first character of a string will be at index zero. Your out memory range error is caused by the fact that the loop stops when less than or equal, causing the index to increase one too many and leave the memory range of the string.
Simply changing the loop from
for (int i = 1; i <= binaryNumber.length(); i++) {
if(binaryNumber.at(i) == '0') {
}
else {
adder = pow(2, i);
total = adder + total;
}
}
To
for (int i = 0; i < binaryNumber.length(); i++) {
if(binaryNumber.at(i) == '0') {
}
else {
adder = pow(2, i);
total = adder + total;
}
}
Will solve the issue.
Because your started from 1 and not 0
for (int i = 1; i <= binaryNumber.length(); i++)
Try with that
for (int i = 0; i < binaryNumber.length(); i++)
void decimaltobin()
{
binaryNum = 0;
m = 1;
while (num != 0)
{
rem = num % 2;
num /= 2;
binaryNum += rem * m;
m *= 10;
}
}
Just wondering if there was an easy fix to get this function to print an 8-bit binary number instead of a 4-bit number, e.g. 0000 0101 instead of 0101.
As mentioned in the comments, your code does not print anything yet and the data type of binaryNum is not clear. Here is a working solution.
#include <iostream>
using namespace std;
void decToBinary(int n)
{
// array to store binary number
int binaryNum[32];
// counter for binary array
int i = 0;
while (n > 0) {
// storing remainder in binary array
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
// printing the required number of zeros
int zeros = 8 - i;
for(int m = 0; m < zeros; m++){
cout<<0;
}
// printing binary array in reverse order
for (int j = i - 1; j >= 0; j--)
cout << binaryNum[j];
}
// Driver program to test above function
int main()
{
int n = 17;
decToBinary(n);
return 0;
}
The code implements the following:
Store the remainder when the number is divided by 2 in an array.
Divide the number by 2
Repeat the above two steps until the number is greater than zero.
Print the required number of zeros. That is 8 - length of the binary number. Note that this code will work for numbers that can be expressed in 8 bits only.
Print the array in reverse order now
Ref
Maybe I am missing your reason but why do you want to code from scratch instead of using a standard library?
You may use standard c++ without having to code a conversion from scratch using for instance std::bitset<NB_OF_BITS>.
Here is a simple example:
#include <iostream>
#include <bitset>
std::bitset<8> decimalToBin(int numberToConvert)
{
return std::bitset<8>(numberToConvert);
}
int main() {
int a = 4, b=8, c=12;
std::cout << decimalToBin(a)<< std::endl;
std::cout << decimalToBin(b)<< std::endl;
std::cout << decimalToBin(c)<< std::endl;
}
It outputs:
00000100
00001000
00001100
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
currently I am working on power digit sum in C++. my program is working properly but it gives inappropriate output.
#include<iostream>
#include<math.h>
using namespace std;
long double calculate(long double n)
{
long double i,j,temp = 0,sum = 0;
while(n != 0)
{
temp = fmod(n,10);
sum = sum + temp;
n = n / 10;
}
return sum;
}
int main()
{
long double i,j,n = 1000,temp = 1,value = 0;
for(i = 1;i <= n;i++)
{
temp = temp * 2;
}
cout << "Multiplication is : " << temp << endl;
value = calculate(temp);
cout.precision(100);
cout << "Sum is : " << value << endl;
return 0;
}
I am getting o/p like this.
Multiplication is : 1.07151e+301
Sum is : 1200.63580205668592182366438692042720504105091094970703125
it shouldn't be in points.it should print in digits.
Representing 2^1000 in binary would take a 1000 bits. Doubles are only 64bits long (long doubles are 80 or 128 bits depending on compiler/architecture). So doubles represent 2^1000 approximately. The input to calculate isn't 2^1000, but rather as close an approximation to it as 80bits allow. That approximation does not contain the lowest digits that calculate would like to sum over.
You can't use any primitive datatype to calculate 2^1000 and later sum of its digits, as its a big number (however, in languages like python and ruby you can do it).
For solving this problem in C/C++, you have to use array (or any other linear data structure like linked list, etc) and apply logic similar to usual pen-paper method of multiplying numbers.
First try to find a bound on number of digits in 2^1000 and then initialize an integer array of size greater than it with all zeroes. Keep the last element to be 1. Now multiply the array (thinking it as a large number such that each digit is in a different cell of the array) with 2, thousand times, taking modulo and carry overs.
Here is the code for above logic:
int ar[303];
int sum =0;
ar[0]=1;
for(int j=1;j<303;j++)
ar[j]=0;
for(int i=1;i<1001;i++)
{
ar[0]=2*ar[0];
for(int k=1;k<303;k++)
ar[k]=2*ar[k] + ar[k-1]/10;
for(int j=0;j<303;j++)
ar[j]=ar[j]%10;
}
for(int i=0;i<303;i++)
sum = sum + ar[i];
cout<<sum;
Hope it helps.
The reason why you are getting your sum with decimal points is because you are dividing a double by 10. This will not result in a clean integer unless the doubles last digit before the decimal point is a zero.
example:
376 / 10 = 37.6
370 / 10 = 37
To solve this change this in your code on line 12:
n = (n-temp)/10;
This will cut the float numbers from your sum at least.
finally i have solved my problem.
#include<iostream>
#include<math.h>
#include<string>
using namespace std;
long double calculate(string n)
{
long double i,j,temp = 0,sum = 0;
for (i = 0;i < n.length();i++)
{
if(n[i] == '.')
{
break;
}
sum = sum + (n[i] - 48);
}
return sum;
}
int main()
{
long double i,j,n = 1000,temp = 1,value = 0;
string str;
temp = pow(2,n);
cout << "Power is : " << temp << endl;
str = to_string(temp);
cout << str << endl;
value = calculate(str);
cout.precision(100);
cout << "Sum is : " << value << endl;
return 0;
}
I have to write a function that accepts an array of integers as arguments
and display back to the user the "unusual" digits. Digits that appear only
in one integer and not the rest, and then sort the array so that the integer
with the largest occurrences of unusual digits is to be moved to the first
element of the array, then followed by the integer with the next
largest number of occurrences of unsual digits.
Input:
113
122
1000
Output:
There is 3 unusual digits:
0 occurs 3 times in 1000
2 occurs 2 times in 122
3 occurs 1 time in 113
Sorted:
1000
122
113
My question is how can I retrieve the integers that were associated with the unusual digits so that I can sort them in the future?
I would like to know which integer digit 0 came from and how many times it occurred in that integer.
Here's what I have so far, I apologize if the code is bad. I am not allowed to use any additional libraries other than iostream and all function calls must be written myself.
#include <iostream>
using namespace std;
void getUncommon(int* iAry, int size) {
const int size2 = 10;
int* tmpAry = new int[size];
int totalCount[size2] = { 0 };
int currentCount[size2] = { 0 };
int totalUncommon = 0;
int i, j;
for (i = 0; i < size; i++) {
tmpAry[i] = iAry[i];
if (tmpAry[i] < 0)
tmpAry[i] *= -1;
for (j = 0; j < size2; j++)
currentCount[j] = 0;
if (tmpAry[i] == 0) {
currentCount[0] = 1;
}
while (tmpAry[i] / 10 != 0 || tmpAry[i] % 10 != 0){
currentCount[tmpAry[i] % 10] = 1;
tmpAry[i] /= 10;
}
for (j = 0; j < size2; j++) {
totalCount[j] += currentCount[j];
}
}
for (i = 0; i < size2; i++) {
if (totalCount[i] == 1) {
totalUncommon++;
}
}
cout << "Total of uncommon digits: " << totalUncommon << endl
<< "Uncommon digits:\n";
if (totalUncommon == 0) {
cout << "\nNo uncommon digits found.";
}
else {
for (i = 0; i < size2; i++) {
if (totalCount[i] == 1) {
cout << i << endl;
}
}
}
return;
}
int main(){
int* my_arry;
int size;
int i;
cout << "How many integers? ";
cin >> size;
my_arry = new int[size];
for (i = 0; i < size; i++) {
cout << "Enter value #" << i + 1 << " : ";
cin >> my_arry[i];
}
cout << "\nThe original array:" << endl;
for (i = 0; i < size; i++) {
cout << my_arry[i] << endl;
}
cout << "\nCalling function -\n" << endl;
getUncommon(my_arry, size);
delete[] my_arry;
return 0;
}
Thanks ahead of time.
You can create a map with the digits 0 1 2 ... 9 as the key, and a pair of pointer to/index of integer containing the digit and number of occurrences of the digit in the integer as the value of the key-value pair.
Start iterating on the integer list, extracting the digits and their number of occurrences from each integer. You can do that by either using the modulo operator, or using string functions (after converting the integer to string).
Now, for each integer, access the map of digits for all the digits in the integer, and if the value is uninitialised, update the value with the pointer/index to this integer and the number of occurrences of the digit in this integer. If the map entry is already populated, that means that it's not an "unusual" digit. So you can mark that map entry with a marker that conveys that this particular digit is not "unusual" and hence no need to update this entry.
After iterating over the entire integer list in this manner, you can iterate the map to find out which digits are unusual. You can also access the containing integer from the pointer/index in the value portion of the map's key-value pair. You can sort these entries easily using any sorting algorithm (since the number of values to be sorted is very small, no need to worry about time complexity, pick the easiest one) on the number of occurrences value.