Task similar to happy number - c++

I am solving a c++ algorithmic problem and I don't know why I don't get a right answer. The problem consists in : there is given a row of n numbers. The you need to take each number and add the square of its digits till you get the sum 4 or 1. Then you need to print how many times you have added that number. His is an example: you have a row of 2 numbers: 89 and 68. You start with 89:
64 + 81 = 145;(1) 1 + 16 + 25 = 42;(2) 16 + 4 = 20;(3) 4 + 0 = 4;(4)
and we stop because it is 4. We need to print 4 because we added 4 times again and again till we got 4 or 1.The same with 68. My code is in c++ but it uses for files c.
#include<stdio.h>
#include<math.h>
FILE *f,*g;
int n,i,a[500],sqr,nr;
int main()
{
f = fopen("unupatru.in","r");
fscanf(f,"%d\n",&n);
for(i=1;i<=n;i++)fscanf(f,"%d",&a[i]);
fclose(f);
for(i=1;i<=n;i++)
{
nr=0;
sqr=0;
while(sqr!=4 || sqr !=1)
{
while(a[i])
{
sqr+=pow(a[i]%10,2);
a[i]/=10;
}
a[i]=sqr;
nr++;
}
g=fopen("unupatru.out", "w");
fprintf(g,"%d\n",nr);
fclose(g);
}
return 0;
}
Please help me
The problem with my code is that when I click on run and compile it doesn't stop running please help

Not sure is enough but...
You should put sqr = 0 also inside the external while and (as pointed by Igor Tandetnik) modify the test using && instead ||
Or better: you shuold use do/while (with sqr=0 only inside)
do
{
sqr=0;
while(a[i])
{
sqr+=pow(a[i]%10,2);
a[i]/=10;
}
a[i]=sqr;
nr++;
}
while(sqr!=4 && sqr !=1)

#include<iostream>
#include<cmath>
#include<fstream>
using namespace std;
FILE *f,*g;
int n,i,a[500],sqr,nr,b[500];
int main()
{
f = fopen("unupatru.in","r");
fscanf(f,"%d\n",&n);
for(i=1;i<=n;i++)fscanf(f,"%d",&a[i]);
fclose(f);
for(i=1;i<=n;i++)
{
nr=0;
sqr=0;
while(sqr!=4 && sqr !=1)
{
sqr=0;
while(a[i])
{
sqr+=pow(a[i]%10,2);
a[i]/=10;
}
a[i]=sqr;
nr++;
b[i]=nr;
}
}
g=fopen("unupatru.out", "w");
for(i=1;i<=n;i++)
fprintf(g,"%d ",b[i]);
fclose(g);
return 0;
}

Related

staircase child always getting a 0?

Hi I am a beginner in recursions.
Question:
A child is running up a staircase he can hop 1, 2 or 3 steps at a time I need to find and return the number of ways he can climb a certain stair number?
My approach:
I am trying to divide the problem into smaller base cases and add 1 when a correct ans is reached.
My code:
void helper(int n ,int& a){
if(n==0){
a = a+1;
return;
}
if(n<0)
return;
helper(n-1,a);
helper(n-2,a);
helper(n-3,a);
}
int staircase(int n){
int ans = 0;
helper(n,ans);
return ans;
}
Problem:
I seem to be getting only 0 as answer?
I dont see why your code won't work. Here is a demo of it working with some changes: Live Demo
It is recommended that you don't pass in a reference and rather make each sub-problem which is either step 1, 2 or 3 self contained problems where you combine the results and that is the final answer similar to:
int staircase_without_reference(int n)
{
if(n == 0) return 1;
if(n < 0) return 0;
return staircase(n - 1) + staircase(n - 2) + staircase(n - 3);
}
This returns the similar to your program without the reference parameter.

output error: different outputs on two different compilers: Prime Cryptarithm USACO

The following cryptarithm is a multiplication problem that can be solved by substituting digits from a specified set of N digits into the positions marked with *. If the set of prime digits {2,3,5,7} is selected, the cryptarithm is called a PRIME CRYPTARITHM. Example:
* * *
x * *
-------
* * * <-- partial product 1
* * * <-- partial product 2
-------
* * * *
These stars can be replaced only by a defined set of integers N which is given by the USACO grader.
The partial products must be three digits long.
Data given:
4 /* <-- This is the given size of set N from which the multiplicand and multiplier is taken */
2 3 5 7 /* <-- Set N */
The task is to calculate the number of possible outcomes and output the number.
My question:
In my compiler,The output is 0,which is correct,but in the USACO grader my program outputs 1. I am not able to identify what the problem is.
Could someone help me resolve this issue?
Thanks in advance.
MY PROGRAM CODE:
#include <iostream>
#include <fstream>
using namespace std;
int *sortInput(int arrSetN[], int numofDigs)
{
for(int ictr=0;ictr<numofDigs;ictr++)
{
for(int jctr=ictr+1;jctr<numofDigs;jctr++)
{
if(arrSetN[ictr]>arrSetN[jctr])
{
swap(arrSetN[ictr],arrSetN[jctr]);
}
}
}
return arrSetN;
}
bool checkNum(int num,int arrSetN[],int numofDigs)
{
int countDigits=0,tempNum=num,ictr=0,jctr=0;
int *arrDigits,*digitTally;
/*
Counting the number of digits in num.
*/
for(;tempNum>0;)
{
tempNum=tempNum/10;
countDigits++;
}
arrDigits=new int[countDigits];
digitTally=new int[countDigits];
/*
making digitTally = 0
*/
for(ictr=0;ictr<countDigits;ictr++)
digitTally[ictr]=0;
/*
retrieving the digits of num.
*/
for(ictr=0;ictr<countDigits;ictr++)
{
arrDigits[ictr]=num%10;
num=num/10;
}
/*
checking if all digits of num are part of set N.
*/
for(ictr=0;ictr<countDigits;ictr++)
{
for(jctr=0;jctr<=numofDigs;jctr++)
{
if(arrDigits[ictr]==arrSetN[jctr])
digitTally[ictr]=1;
}
}
for(int cfc=0;cfc<countDigits;cfc++)
{
if(digitTally[cfc]==0)
return false;
}
return true;
}
int main()
{
ofstream fout("crypt1.out");
ifstream fin("crypt1.in");
int numofDigs,ictr=0,a,b,c,d, e,p1,p2,sum,p2test;
int actr=0,bctr=0,cctr=0,dctr=0,ectr=0,tally=0;
bool sumCheck,p1Check,p2Check;
fin>>numofDigs;
int *arrSetN;
arrSetN = new int[numofDigs];
for(ictr=0;ictr<numofDigs;ictr++)
{
fin>>arrSetN[ictr];
}
arrSetN=sortInput(arrSetN,numofDigs);
for(actr=0;actr<numofDigs;actr++)
{
a=arrSetN[actr];
for(bctr=0;bctr<numofDigs;bctr++)
{
b=arrSetN[bctr];
for(cctr=0;cctr<numofDigs;cctr++)
{
c=arrSetN[cctr];
for(dctr=0;dctr<numofDigs;dctr++)
{
d=arrSetN[dctr];
for(ectr=0;ectr<numofDigs;ectr++)
{
e=arrSetN[ectr];
p1=((a*100)+(b*10)+c)*e;
p2=((a*1000)+(b*100)+(c*10))*d;
p2test=((a*100)+(b*10)+c)*d;
p1Check=checkNum(p1,arrSetN,numofDigs);
p2Check=checkNum(p2test,arrSetN,numofDigs);
if(p1>999 || p2test>999 || p1<100 || p2test<100)
{
continue;
}
sum=p1+p2;
sumCheck=checkNum(sum,arrSetN,numofDigs);
if(sumCheck==true && p1Check==true && p2Check==true)
{
tally++;
//fout<<a<<" "<<b<<" "<<c<<" "<<d<<" "<<e;
//fout<<"\t"<<p1<<" "<<p2<<" "<<sum<<"\n";
}
}
}
}
}
}
fout<<tally<<"\n";
}
Generally, when the results of a program are different with different compilers, that usually means somewhere in your program you are running into Undefined Behavior.
In your case, the comparison of j<=numofDigs in checkNum is incorrect. You are accessing past the end of arrSetN when j==numofDigs. Since this is undefined, you can get different results.
There may be other similar places, but this is the one I noticed.

getting TLE from mouse maze in c++

I keep getting TLE in this question.I have tried to use scanf printf instead of cin cout but it didnt work.Then,I tried another question which has same
description,the only different is input N which means test case change from 1000 to 10^6.However, I got all AC there.I just cant figure out why.
following is the question
Description
Write a program that simulates a mouse in a maze. The program must count the steps taken by the mouse from the starting point to the final point.
The maze type is shown in following figure:
S$###
$$#$$
$$$##
##$$F
it consists of S (starting point), #(walls), $(road) and F (final point).
In above case, it needs 7 steps from S to F as following figure,
S$###
$$#$$
$$$##
##$$F
and the mouse can move in the four directions: up, down, left, right. There may be more than one way to reach final point, the program only need to print the least steps.
If there is no way from S to F, then print -1.
Input
The first line has an integer N(1<=N<=1000), which means the number of test cases.
For each case, the first line has two integers. The first and second integers R and C (3<=R, C<=500) represent the numbers of rows and columns of the maze, respectively. The total number of elements in the maze is thus R x C.
The following R lines, each containing C characters, specify the elements of the maze.
Output
Print out the least steps for each case, and there is a new line character at the end of each line.
Sample Input
3
4 5
S$###
$$#$$
$$$##
##$$F
4 5
S$$##
#$$$#
#$#$#
#$$$F
4 5
##S$#
$##$$
$$$##
#F###
Sample Output
7
7
-1
following is my code
#include <iostream>
#include <climits>
using namespace std;
int least_step;
void maze(char a[501][501],int,int,int,int,int);
#define wall '#'
int main(){
int ncase;
cin>>ncase;
char a[501][501];
while(ncase--){
int num1,num2;
cin>>num1>>num2;
least_step = INT_MAX;
int si,sj;
for(int i=0;i<num1;i++){
for(int j=0;j<num2;j++){
cin >> a[i][j];
if(a[i][j]=='S'){
si = i;
sj = j;
}
}
}
maze(a,si,sj,num1,num2,0);
if(least_step==INT_MAX){
least_step = -1;
}
cout<<least_step<<endl;
}
return 0;
}
void maze(char a[501][501],int i,int j,int num1,int num2,int step){
if(a[i][j] == 'F'){
if(step<least_step){
least_step = step;
}
return;
}
a[i][j] = wall;
if(i+1<num1&&a[i+1][j] != wall){
maze(a,i+1,j,num1,num2,step+1);
}
if(j+1<num2&&a[i][j+1] != wall){
maze(a,i,j+1,num1,num2,step+1);
}
if(i-1>=0&&a[i-1][j] != wall){
maze(a,i-1,j,num1,num2,step+1);
}
if(j-1>=0&&a[i][j-1] != wall){
maze(a,i,j-1,num1,num2,step+1);
}
a[i][j] = '$';
return;
}

(C++) fstream win32 exception occured in title.exe [6284]

So I made the following algorithm to solve a problem, but I don't understand why it crashes when I use fstream instead of iostream. When I use lower numbers, for example (input e.g.: 1 4 5 ) it works perfectly with fstream, but if I use some larger input numbers (e.g: 3 987654300 210 ),it says "Process returned -1073741819 (0xC0000005)". If I use iostream, it works great even with 9 digit inputs.
Yes, I have the parola.in and parola.out in the same folder with the .cpp/.exe and the .in has the input numbers and everything.
Ignore the algorithm and the comments, and just pay attention at the use of "fout" and "fin" please.
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream fin("parola.in");
ofstream fout("parola.out");
int a,b,k; //VARIABILE ORIGINALE
int ord=1; //NUMARUL DE ORDINE AL VECTORILOR
int cifa=0,cifb=0; //NUMARUL DE CIFRE AL NUMERELOR A SI B
int nrA[18],nrB[10]; //VECTORII CE CONTIN CIFRELE NUMERELOR A SI B
int temp[9]; //VECTORUL CE CONTINE CIFRELE NR. A IN ORDINE INVERSA
fin>>k>>a>>b;
while (a>0)
{
temp[ord]=a%10;
a/=10;
ord++;
cifa++;
}
ord=1; //RESET NR ORDINE
while (b>0)
{
nrB[ord]=b%10;
b/=10;
ord++;
cifb++;
}
for (int topkek=1; topkek<=cifa; topkek++)
{
nrA[topkek]=temp[cifa+1-topkek]; //ORDONAREA CIFRELOR LUI A CRESCATOR, IN VECTORUL nrA
}
for (int zomtan=1; zomtan<=k; zomtan++)
{
fout<<nrA[zomtan];
nrA[zomtan]=-1;
}
fout<<nrB[1];
nrB[1]=-1;
for (int zomtan2=cifa+1; zomtan2<=18; zomtan2++)
{
nrA[zomtan2]=-1;
}
for (int zomtan3=cifb+1; zomtan3<=10; zomtan3++)
{
nrB[zomtan3]=-1;
}
for (ord=1; ord<=9; ord++)
{
if (nrA[ord+k]!=-1)
{
fout<<nrA[ord+k];
}
if (nrB[ord+1]!=-1)
{
fout<<nrB[ord+1];
}
}
return 0;
}
The problem can occurs beause, as I suppose, you use 1 based arrays instead of propper 0 based
for (int zomtan2=cifa+1; zomtan2<=18; zomtan2++)
{
nrA[zomtan2]=-1;
}
the problem will always occurs because you have wrote zomtan2<=18
and your array declaration is int nrA[18] wich I have said previously always casues problems.
These errors are everywhere in your code, so i suggest you to rewrite the program

dynamic programming: coin change

I have as an input:
the number of testcases
an amount of money
As output I need:
The number different coins we have and the value of each coin.
The program should determine whether there is a solution or not, so the output should be either a "yes" or a "no".
I wrote the program using dynamic programming, but it only works when I enter one testcase at a time If i write let's say 200 testcases at once, the output isn't always right.
I'm assuming that I have an issue with incorrectly saved state between test cases.
My question is, how could I solve this problem? I'm only asking for some advice.
Here's my code:
#include<iostream>
#include<stdio.h>
#include<string>
#define max_muenzwert 1000
using namespace std;
int coin[10];//max. 10 coins
int d[max_muenzwert][10];//max value of a coin und max. number of coins
int tabelle(int s,int k)//computes table
{
if(d[s][k]!=-1) return d[s][k];
d[s][k]=0;
for(int i=k;i<=9&&s>=coin[i];i++)
d[s][k]+=tabelle(s-coin[i],i);
return d[s][k];
}
int main()
{
int t;
for(cin>>t;t>0;t--)//number of testcases
{
int n; //value we are searching
scanf("%d",&n)==1;
int n1;
cin>>n1;//how many coins
for (int n2=0; n2<n1; n2++)
{
cin>>coin[n2];//value of coins
}
memset(d,-1,sizeof(d));//set table to -1
for(int i=0;i<=9;i++)
{
d[0][i]=1;//set only first row to 1
}
if(tabelle(n,0)>0) //if there's a solution
{
cout<<"yes"<<endl;
}
else //no solution
{
cout<<"no"<<endl;
}
}
//system("pause");
return 0;
}
As you can see you have variable number of coins, which you are taking input using this line: cin>>n1;//how many coins. But in the tabelle method you are always looping through 0 - 9, which is wrong. You should only loop through 0 - n1. Try this test case:
2
10
2
2 5
10
1
9
For the second test set your answer should be no but your program will say yes as it will find 5 in the second element of your coin array.
for(int i=k;i<=9&&s>=coin[i];i++)
d[s][k]+=tabelle(s-coin[i],i);
Here, if coin[i] < s, then the entire loop will break, while you only need to skip this coin.
P.S. Please bother yourself with proper code formatting.