I am working on a complete search problem, and have looked through the code, but could not figure out why my program keeps coming in with an empty output file error. Could anyone please help me find why this is happening? The problem statement is below, and then after that is my code.
PROBLEM STATEMENT: Palindromes are numbers that read the same forwards as backwards. The number 12321 is a typical palindrome.
Given a number base B (2 <= B <= 20 base 10), print all the integers N (1 <= N <= 300 base 10) such that the square of N is palindromic when expressed in base B; also print the value of that palindromic square. Use the letters 'A', 'B', and so on to represent the digits 10, 11, and so on.
Print both the number and its square in base B.
MY CODE:
/*
USER: agnegru1
TASK: palsquare
LANG: C++11
*/
#include <iostream>
#include <cmath>
#include <algorithm>
#include <fstream>
#include <string>
using namespace std;
int convert(string num, int base1)
{
int sum = 0;
for (int i = num.size() - 1; i >= 0; i--)
sum += num[i] * pow(base1, num.size() - i);
return sum;
}
bool is_pal(int number)
{
if (number % 2 == 0)
{
int mid = (to_string(number).size()) / 2;
string str_num = to_string(number);
string half1;
for (int i = 0; i < mid; i++)
half1 += str_num[i];
string half2;
for (int i = str_num.size()-1; i > mid-1; i--)
half2 += str_num[i];
if (half1 == half2)
return true;
return false;
}
else
{
int mid1 = (to_string(number).size() - 1) / 2;
int mid2 = (to_string(number).size() + 1) / 2;
string str_num = to_string(number);
string half1;
for (int i = 0; i < mid1; i++)
{
half1 += str_num[i];
}
string half2;
for (int i = str_num.size()-1; i > mid2-1; i--)
{
half2 += str_num[i];
}
if (half1 == half2)
return true;
return false;
}
}
int main()
{
ofstream fout("palsquare.out");
ifstream fin("palsquare.in");
int base;
fin >> base;
for (int i = 1; i < 300; i++)
{
if (is_pal(convert(to_string((pow(i, 2))), base)))
{
fout << convert(to_string(i), base) << " " << convert(to_string(pow(i, 2)), base) << "\n";
}
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire