This code gives unwanted '0' in output (C++) - c++

I was making a program which coverts a list of prime numbers into yes-no format. By yes-no I mean that 2, 3, 5, 7, 11 gets converted into 1101010001 where '0' represents composite number and '1' represents prime number. This means that 2 is prime, 3 is prime, 4 is composite, 5 is prime, 6 is composite and so on. This is my code:
#include<iostream>
#include<fstream>
#include<cmath>
#include<string>
using namespace std;
unsigned long long int sti (string inp) //This function just converts string to integer
{
unsigned long long int size = inp.size();
unsigned long long int ret = 0 ;
for (unsigned long long int i = 0; i < size; i++)
{
ret += pow(10, i) * stoi(to_string(inp[size-i-1]));
}
return ret;
}
int main()
{
ifstream ifs("1.txt");
string temp = "";
string ret = "";
unsigned long long int inp1 = 0;
unsigned long long int inp2 = 0;
ifs >> temp;
inp1 = sti(temp);
ret+='1';
int diff=0;
while(true)
{
inp2= inp1;
ifs >> temp;
inp1 = sti(temp);
if(inp1==inp2)
{
break;
}
diff = inp1-inp2-1;
for(int i=0; i<diff; i++)
{
ret+='0';
}
ret+='1';
}
cout<< ret;
}
But when I try to convert first 10 primes, ie - 2,3,5,7,11,13,17,19,23,29, The code outputs 1101010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001010001010001000001
The code gives unexpected zeroes between 7 and 11.
Can anyone please help me with what is happening?

Related

Recursively convert a given string to the number it represents

Write a recursive function to convert a given string into the number it represents. That is input will be a numeric string that contains only numbers, you need to convert the string into corresponding integer and return the answer.
I only get the first digit of my string as the output. E.g "1234" as 1 or "231" as 2. Which makes me think there may be an error in my recursive function (the base case seems fine though) but I cant figure out what it is.
#include <math.h>
#include <cmath>
#include <iostream>
using namespace std;
int lenght (char input[]){
int count = 0;
for (int i=0 ; input[i] != '\0' ; i++){
count++;
}
return count;
}
//helper
int stringToNumber(char input[], int start ) {
int len = lenght(input);
//base case
if(start ==0){
return int (input[start]) - 48;
}
int a = stringToNumber(input , start+1);
int b = int(input[start]) - 48;
int k = pow(10, len-1);
return k*b + a;
}
int stringToNumber(char input[]) {
return stringToNumber(input, 0);
}
int main() {
char input[50];
cin >> input;
cout << stringToNumber(input) << endl;
}
Sample Input 1 :
1231
Sample Output 1:
1231
What my code generates: 1
Converting string to decimal integer - is actually converting a number from decimal to binary form. I.e. each digit is a mod of 10.
I.e. for the 1234 it can be done done like 1 * 1000 + 2 * 100 + 3 * 10 + 4
or (1*10)+2, (12*10)+3, (123*10)+4. Second algorithm can be implemented like next recursive function:
constexpr uintmax_t atou(const char* a,uintmax_t ret = 0) noexcept {
return '\0' == *a ? ret : atou(a+1, (ret * 10) + ( *a - '0') );
}
i.e. you are scanning a string for digits, until '\0' end of line character (or std::isspace for example), if more digits in the string multiply result on 10 and add the next digit to the result.
static_assert( 1234 == atou("1234"), "1234 expected" );
Try this code:
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
int convert(char c[]) {
if (c[0]=='\0') {
return 0;
} else {
int d = strlen(c) - 1;
int p = pow(10, d);
int k = int(c[0]) - 48; // ASCII value of '0' is 48
return (k * p + convert(c + 1));
}
}
int main() {
int n;
cin >> n;
char c[n];
cin >> c;
cout << convert(c);
}
public class solution {
public static int convertStringToInt(String input){
// Write your code here
if(input.length()<1)
{
return 0;
}
return input.charAt(input.length()-1)-'0'+(10*convertStringToInt(input.substring(0,input.length()-1)));
}
}

Wrong output with std::string using stoul, on integer array

Hi, I'm having trouble trying to convert a line of numbers, e.g.: 100 101 102, to (stoul) an dynamically allocated unsigned integer; the expected is that I can access number by number as an array, in an variable length input.
#include <iostream>
#include <new>
#include <string> //Memset
int console(){
std::string console_buffer;
unsigned long int* integersConverted = NULL;
unsigned int integersNumberOf = 0;
for( ; ; ){
std::getline(std::cin, console_buffer);
integersConverted = console_defaultSyntaxProcessing(console_buffer, &integersNumberOf);
std::cout << "Found the following integers from conversion: ";
for(unsigned int debug_tmp0 = 0; debug_tmp0 < integersNumberOf; debug_tmp0++){
std::cout << integersConverted[debug_tmp0] << " ";
std::cout << std::endl;
}
delete integersConverted;
integersConverted = NULL;
}
return 0;
}
unsigned long int* console_defaultSyntaxProcessing(std::string console_buffer, unsigned int* integersNumberOfUpdate){
*integersNumberOfUpdate = 0;
unsigned int integersNumberOf = 0;
unsigned long int* integersFound = NULL;
integersFound = new unsigned long int(sizeof(unsigned long int) * 1024);
std::size_t stringPosition = 0;
for( ; stringPosition < console_buffer.length() && integersNumberOf < 1024; ){
integersFound[integersNumberOf] = std::stoul(console_buffer, &stringPosition, 10); //10 = Decimal
integersNumberOf++;
}
*integersNumberOfUpdate = integersNumberOf;
return integersFound;
}
I'm getting correct value if I input only one number, but the whole 1024 array is printed if I input two numbers or more and all positions get the first integer. I've tried to manually set the function std::string to constant, zero the console_buffer.length() so it finds '\0', etc; unfortunately not worked..
UPDATE --- 5 minutes after the topic first posting;
The problem is, as Yashas answered, at console_defaultSyntaxProcessing for loop; stoul &stringPosition returns number of characters read from, not the position of std::string.
Another problem using stoul is, if I input 100 ( 101, it doesn't work, so follows the fixed code but shall not be used.
As lamandy suggested, use std::stringstream instead.
std::size_t stringPosition = 0;
std::size_t stringPositionSum = 0;
for( ; stringPosition < console_buffer.length() && integersNumberOf < 1024; ){
try{
integersFound[integersNumberOf] = std::stoul(&console_buffer[stringPositionSum], &stringPosition, 10);
integersNumberOf++;
stringPositionSum = stringPositionSum + stringPosition;
}
catch(std::exception& exception){
break;
} //This catch will be used constantly by this buggy code.
for( ; stringPosition < console_buffer.length() && integersNumberOf < 1024; ){
integersFound[integersNumberOf] = std::stoul(console_buffer, &stringPosition, 10); //10 = Decimal
integersNumberOf++;
}
does not do what you want.
You are passing the same string to std::stoul again and again. Your std::stoul function keeps reading the first number every time. When you had just one number, the stringPosition < console_buffer.length() caused your loop to stop. When you have more than one number, stringPosition will never exceed console_buffer.length().
The second parameter of std::stoul does not take where in the string to start reading from; it gives you the number of characters processed.
For the task you are dealing with, stringstream is what you need.
#include <iostream>
#include <sstream>
#include <array>
int main ()
{
std::istringstream console_buffer("123 345 3 5 2 3 4 5 6 7 7 232 34 332 234 55");
std::array<unsigned long, 1024> integerArray;
size_t count = 0;
while(console_buffer && count < integerArray.size())
console_buffer >> integerArray[count++];
for(int i = 0; i < count; i++)
std::cout<<integerArray[i] << ' ';
return 0;
}
Consider using std::vector and std::stringstream to ease your job.
std::vector<unsigned long int> StringToIntegerVector(const std::string& input)
{
std::istringstream iss(input);
unsigned long int temp;
std::vector<unsigned long int> results;
while (iss >> temp)
results.push_back(temp);
return results;
}

How to generate the nth number that consists only of even digits?

I'm novice to Programming. I can find numbers consisting of even digits but my algorithm complexity is O(n). For large n my algorithm is too slow. So I need a more efficient algorithm. Can anyone help me?
For example, the first numbers with even digits are 0 , 2 , 4 , 6 , 8 , 20 , 22 , 24 , 26 , 28 , 40 etc. 2686 is another example of a number with even digits.
Here is my code: http://ideone.com/nsBzej
#include<bits/stdc++.h>
using namespace std;
long long int a[10],b[20];
long long int powr(int i)
{
long long int ans=5;
for(int j=2;j<=i;j++)
{
ans=ans*5;
}
return ans;
}
int main()
{
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
long long int n,s,sum,p;
int t;
cin>>t;
for(int j=1;j<=t;j++)
{
s=20,sum=0;
a[1]=0, a[2]=2, a[3]=4, a[4]=6, a[5]=8;
for(int i=1;i<=17;i++)
{
b[i]=s;
s=s*10;
}
cin>>n;
for(int i=17;i>=1;i--)
{
p=powr(i);
while(p<n)
{
sum=sum+b[i];
n=n-p;
}
}
printf("Case %d: %lld\n",j,sum);
}
}
It is complexity O(n). But I get wrong verdict.
#include <stdio.h>
int main(void){
unsigned long long nth = 1000000000000ULL-1;//-1: 1 origin
unsigned long long k[30] = {0, 5};//28:Log10(ULL_MAX)/Log10(5) + 1
unsigned long long sum = k[1];
unsigned long long temp = 4;//4 : 2,4,6,8
int i;
//make table
for(i = 1; i < 30 ; ++i){
if(k[i] == 0){
temp *= 5;//5 : 0,2,4,6,8 , 2digits: 4*5, 3digits: 4*5*5
sum += temp;
k[i] = sum;
}
if(k[i] > nth)
break;
}
while(--i){//The same basically barakmanos
int n = nth / k[i];
printf("%d", n * 2);
nth -= n * k[i];
}
printf("%d\n", nth * 2);
return 0;
}

How to grab first digit of an int in an int array?

I have an int array called doubledNumbers and if a number in this array is greater than 9, I want to add the digits together. (example, 16 would become 1+6=7, 12 would become 3, 14 would become 5, etc)
Lets say I had the following numbers in doubledNumbers:
12 14 16 17
I want to change the doubledNumbers to:
3 5 7 8
I'm unsure how to do this for an int array as I get the error
invalid types 'int[int]' for array subscript
This is the code I have (thrown in a for loop):
if (doubledNumbers[i]>9) {
doubledNumbers[i]=doubledNumbers[i][0]+doubledNumbers[i][1];
There is nothing like decimal digits in an int. There are (mostly 32 or 64) binary digits (bits) and the base of 2 is not commensurable with the base of 10. You’ll need to divide your numbers by 10 to get decimal digits.
unsigned int DigitSum(unsigned int input, unsigned int base = 10)
{
unsigned int sum = 0;
while(input >= base)
{
sum += input % base;
input /= base;
}
sum += input;
return sum;
}
I used unsigned int. The example cannot be directly used for negative numbers but the modification is not difficult.
You can use something like this
#include <iostream>
using namespace std;
int sumofdigits(int);
int main()
{
// your code goes here
int a[5] ={12,14,15,16,17};
for(int i=0;i<5;i++)
{
int m=sumofdigits(a[i]);
cout <<m<<" ";
}
return 0;
}
int sumofdigits(int n)
{
int sum=0;
while(n!=0)
{
int d=n%10;
sum=sum+d;
n=n/10;
}
return sum;
}
// % operator is used for calculating remainder.
You can do like this,
#include<iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int a[5]={1,2,5,11,12};
int length = sizeof(a)/sizeof(int);
for(int i=0;i<length;i++)
{
if ( a[i] >9 )
{
stringstream ss;
ss << a[i];
string a1 = ss.str();
const char * s = a1.c_str();
int sum=0;
while (*s !='\0')
{
cout<<*s<<endl;
sum += (*s - '0');
s++;
}
cout<<"num:"<< sum <<"\n";
}
}
}
int A[2];
A[0] = 2;
A[1] = 10;
for (int i=0;i<2;i++) {
if (a[i] > 9) {
int b = a[i]%10;
int c = a[i]/10;
int d = b+c;
cout << d;
}
}
It's only for two digit numbers(10 -99) and for more than that (after 99) we will have to change logic.

reverse the position of integer digits?

i have to reverse the position of integer like this
input = 12345
output = 54321
i made this but it gives wrong output e.g 5432
#include <iostream>
using namespace std;
int main(){
int num,i=10;
cin>>num;
do{
cout<< (num%i)/ (i/10);
i *=10;
}while(num/i!=0);
return 0;
}
Here is a solution
int num = 12345;
int new_num = 0;
while(num > 0)
{
new_num = new_num*10 + (num % 10);
num = num/10;
}
cout << new_num << endl;
Your loop terminates too early. Change
}while(num/i!=0);
to
}while((num*10)/i!=0);
to get one more iteration, and your code will work.
If you try it once as an example, you'll see your error.
Input: 12
first loop:
out: 12%10 = 2 / 1 = 2
i = 100
test: 12/100 = 0 (as an integer)
aborts one too early.
One solution could be testing
(num % i) != num
Just as one of many solutions.
Well, remember that integer division always rounds down (or is it toward zero?) in C. So what would num / i be if num < 10 and i = 10?
replace your while statement
with
while (i<10*num)
If I were doing it, I'd (probably) start by creating the new value as an int, and then print out that value. I think this should simplify the code a bit. As pseudocode, it'd look something like:
output = 0;
while (input !=0)
output *= 10
output += input % 10
input /= 10
}
print output
The other obvious possibility would be to convert to a string first, then print the string out in reverse:
std::stringstream buffer;
buffer << input;
cout << std::string(buffer.str().rbegin(), buffer.str().rend());
int _tmain(int argc, _TCHAR* argv[])
{
int x = 1234;
int out = 0;
while (x != 0)
{
int Res = x % (10 );
x /= 10;
out *= 10;
out += Res;
}
cout << out;
}
This is a coding assignment for my college course. This assignment comes just after a discussion on Operator Overloading in C++. Although it doesn't make it clear if Overloading should be used for the assignment or not.
The following code works for a two-digit number only.
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
cout << (n%10) << (n/10);
return 0;
}
int a,b,c,d=0;
cout<<"plz enter the number"<<endl;
cin>>a;
b=a;
do
{
c=a%10;
d=(d*10)+c;
a=a/10;
}
while(a!=0);
cout<<"The reverse of the number"<<d<<endl;
if(b==d)
{
cout<<"The entered number is palindom"<<endl;
}
else
{
cout<<"The entered number is not palindom"<<endl;
}
}
template <typename T>
T reverse(T n, size_t nBits = sizeof(T) * 8)
{
T reverse = 0;
auto mask = 1;
for (auto i = 0; i < nBits; ++i)
{
if (n & mask)
{
reverse |= (1 << (nBits - i - 1));
}
mask <<= 1;
}
return reverse;
}
This will reverse bits in any signed or unsigned integer (short, byte, int, long ...). You can provide additional parameter nBits to frame the bits while reversing.
i. e.
7 in 8 bit = 00000111 -> 11100000
7 in 4 bit = 0111 -> 1110
public class TestDS {
public static void main(String[] args) {
System.out.println(recursiveReverse(234));
System.out.println(recursiveReverse(234 ,0));
}
public static int reverse(int number){
int reversedNumber = 0;
int temp = 0;
while(number > 0){
//use modulus operator to strip off the last digit
temp = number%10;
//create the reversed number
reversedNumber = reversedNumber * 10 + temp;
number = number/10;
}
return reversedNumber;
}
private static int reversenumber =0;
public static int recursiveReverse(int number){
if(number <= 0){
return reversenumber;
}
reversenumber = reversenumber*10+(number%10);
number =number/10;
return recursiveReverse(number);
}
public static int recursiveReverse(int number , int reversenumber){
if(number <= 0){
return reversenumber;
}
reversenumber = reversenumber*10+(number%10);
number =number/10;
return recursiveReverse(number,reversenumber);
}
}
I have done this simply but this is applicable upto 5 digit numbers but hope it helps
#include<iostream>
using namespace std;
void main()
{
int a,b,c,d,e,f,g,h,i,j;
cin>>a;
b=a%10;
c=a/10;
d=c%10;
e=a/100;
f=e%10;
g=a/1000;
h=g%10;
i=a/10000;
j=i%10;
cout<<b<<d<<f<<h<<j;
}`