I'm fairly new to programming. I've created a solution to problem 4 on Project Euler. However, my code seems to have a problem and doesn't give me the desired result. The problem at hand is to find the largest palindrome created by multiplying two 3 digit numbers. The code works fine when I start both the loops at 100 (which is to find the largest palindrome obtained by multiplying two 2 digit numbers). My output, in this case, is 90909, whereas it should be 906609. Can anyone please review my code and help me?
#include "iostream"
using namespace std;
int checkPalindrome(int);
int main()
{
int prod;
for(int i=1000;i>0;i--)
for(int j=1000;j>0;j--)
{
prod=i*j;
if(checkPalindrome(prod))
{ cout<<prod;
cout<<endl;
exit(0);
}
}
}
int checkPalindrome(int x)
{
int temp=0,copy;
copy=x;
while(x!=0){
temp=temp*10+(x%10);
x/=10;
}
if(copy==temp)
return 1;
else
return 0;
}
Your are not actually searching for the largest palindrome created by multiplying two 3 digit numbers with your solution but you are instead searching for the first palindrome that the loops find. You can make it right like this:
int main()
{
int prod;
int res = 0;
for (int i = 1000; i > 0; i--)
for (int j = 1000; j > 0; j--)
{
prod = i*j;
if (checkPalindrome(prod) && res < prod)
{
res = prod;
}
}
cout << res;
cout << endl;
exit(0);
}
Related
#include <iostream>
using namespace std;
int main()
{
int n;
n=4;
int arr[n]={1,2,3,8};
int sum;
sum=5;
int curr=0;
cin>>sum;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
curr+=arr[j];
if(curr==sum){
cout<<i;
}
cout<<curr<<endl;
}
}
}
For the given question I need to find the starting and ending index of such a subarray. I have tried the above code but am not able to get the right output. Please guide me.
I think your code only needs some minor modifications. You should add
some code to handle the case where your running sum is greater than the target sum, and you should also re-initialize your running sum correctly.
There may be some efficient solution that is faster than O(n^2), which I am not aware of yet. If someone knows of a solution with a better time complexity, please share with us.
Below is a simple algorithm that has the time complexity of O(n^2). (It may not have the most efficient time complexity for this problem).
This function prints out the 2 indices of the array. The sum of all elements between these 2 indices inclusively will equal the target sum.
void Print_Index_of_2_Elements(int array[], int total_element, int target)
{
// Use Brute force . Time complexity = O(n^2)
for (int i = 0; i < total_element; i++)
{
int running_sum = array[i];
// Second for loop
for (int j = (i + 1) ; j < total_element; j++)
{
if (running_sum == target)
{
cout << "Two indices are: " << i << " and " << j;
return; // Found Answer. Exit.
}
else if ( running_sum > target )
break;
else // running_sum < target
running_sum += array[j];
}
}
cout << " Sorry - no answer was found for the target sum.";
}
If you are someone that is a beginner in subarrays or arrays for the case. Then this code is for you:
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
int sum;
cin>>sum;
int curr=0;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
if(curr==sum){
cout<<i+1<<" "<<j;
return 0;
}
else if (curr>sum){
curr=0;
}
else if(curr<sum){
curr+=arr[j];
}
}
}
return 0;
}
If you have any doubts regarding this, feel free to comment and let me know.
This Question has been answered
So basically, I just wrote down a code to display all the prime numbers below 100. This is the code:
#include <iostream>
using namespace std;
int main()
{
int n=2,i;
cout<<"All Prime numbers below 100 are : \n";
while(n<=100)
{
for(i=2; i<n/2; i++)
{
if (n%i==0)
{
goto restart;
}
else
{
cout<<n<<"\t";
}
}
restart:
n++;
}
return 0;
}
But instead of the output being 2 3 5 7 11 ..... it comes out as:
All prime numbers below 100 are:
7 9 11 11 11 13 13 13 13 15 15 and so on ...
I just want the output to display all prime numbers starting from 2 to 97 without repetitions. thank you.
/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/--/-/-/-/-
I got out of the problem with a slight modification.
#include<iostream>
using namespace std;
int main()
{
int n=2, i;
while(n<=100)
{
for(i=2; i<=n/2; i++)
{
if(n%i==0)
{
goto label;
}
}
cout<<n<<", ";
label:
n++;
}
return 0;
}
Thank you to everyone for your valuable time. (And the reason why I use such beginner type codes is I've just started out on C++ like a week ago. I have so much more codes (like bool, isPrime, etc.) to learn.)
Keeping Cranking 'em codes, fellow coders :D
There is an obvious error in your algorithm. You might be able to find it using a debugger, but I think that a better way would be for you to learn about extracting a function. What you want your main function to do, is exactly: if n is prime: output n. So you should write it that way:
int main()
{
for (int i = 0; i < 100; ++i)
if (is_prime(i))
std::cout << i << std::endl;
}
Of course for that to work you'll need to define the function is_prime:
bool is_prime (int n) {
for (int i = 2; i * i <= n; ++i)
if (n % i == 0)
return false;
return true;
}
Note also that there is no need to check if n is divisible by numbers greater then it's square root. If there are no divisors up to the square root, the next possible divisor is n itself.
As others mentioned, that's not the optimal algorithm to solve this problem, but for small values it's definetely good enough.
Your answer is OK but has two critical errors. Firstly, you output n for each modulo you check. You should only output n if all the modulo checks fail. Also, your boundary condition isn't quite right - it should be <=. Working code with minimal changes would be:
#include <iostream>
using namespace std;
int main()
{
int n=2,i;
cout<<"All Prime numbers below 100 are : \n";
while(n<=100)
{
for(i=2; i<=n/2; i++)
{
if (n%i==0)
{
goto restart;
}
}
cout<<n<<"\t";
restart:
n++;
}
return 0;
}
If you wanted to make slightly cleaner code then dont use goto, use a double for loop and a break. Also your boundary condition for i should be i*i<=n as thats a tighter bound. So something like:
#include <iostream>
int main()
{
cout<<"All Prime numbers below 100 are : \n";
for(int n=2; n<100; ++n)
{
bool isPrime = true;
for(int i=2; i*i<=n; i++)
{
if (n%i==0)
{
isPrime = false;
break;
}
}
if(isPrime)
std::cout<<n<<"\t";
}
}
You are trying to check if each number is prime. Therefor you have to check if it is dividable by a smaller number.
A more efficient way to find all prime numbers up to a maximal number is the Sieve of Erathosthenes:
#include <iostream>
#include <vector>
int main() {
const unsigned int maxNum(100);
std::vector<bool> prime(maxNum, true);
for (unsigned int i(2); i*i < maxNum; ++i) {
if (!prime[i]) continue;
for (unsigned int j(2*i); j < maxNum; j += i) {
prime[j] = false;
}
}
for (unsigned int i(2); i < maxNum; ++i) {
if (prime[i]) std::cout << i << std::endl;
}
return 0;
}
A list of all numbers is created. Each multiple of of each number is removed from this list.
I input p and n (int type) numbers from my keyboard, I want to generate the first p*n square numbers into the array pp[99]. Here's my code:
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int i, j, n, p, pp[19];
cout<<"n="; cin>>n;
cout<<"p="; cin>>p;
i=n*p;
j=-1;
while(i!=0)
{
if(sqrt(i)==(float)sqrt(i))
{
j++;
pp[j]=i;
}
i--;
}
for(i=0; i<n*p; i++)
cout<<pp[i]<<" ";
return 0;
}
But I am encountering the following problem: If I for example I enter p=3 and n=3, it will only show me the first 3 square numbers instead of 9, the rest 6 being zeros. Now I know why this happens, just not sure how to fix it (it's checking the first n * p natural numbers and seeing which are squares, not the first n*p squares).
If I take the i-- and add it in the if{ } statement then the algorithm will never end, once it reaches a non-square number (which will be instant unless the first one it checks is a perfect square) the algorithm will stop succeeding in iteration and will be blocked checking the same number an infinite amount of times.
Any way to fix this?
Instead of searching for them, generate them.
int square(int x)
{
return x * x;
}
int main()
{
int n = 0;
int p = 0;
std::cin >> n >> p;
int limit = n * p;
int squares[99] = {};
for (int i = 0; i < limit; i++)
{
squares[i] = square(i+1);
}
for (int i = 0; i < limit; i++)
{
std::cout << squares[i] << ' ';
}
}
I think that my code works. However, it outputs 01111E5, or 17B879DD, or something like that.
Can someone please tell me why.
I am aware that I set the limit of P instead of 10,001. My code is like that because I start with 3, skipping the prime number 2.
#include <iostream>
bool prime (int i)
{
bool result = true;
int isitprime = i;
for(int j = 2; j < isitprime; j++) ///prime number tester
{
if(isitprime%j == 0) result = false;
}
return result;
}
int main (void)
{
using namespace std;
int PrimeNumbers = 1;
int x = 0;
for (int i = 3 ; PrimeNumbers <=10000; i++)
{
if(prime(i))
{
int prime = i;
PrimeNumbers +=1;
}
}
cout<<prime<<endl;
system ("pause");
return 0;
}
cout<<prime<<endl;
prints the address of the function bool prime (int i), not the variable you declared. Just rename the function or the variable (note that you'll also have to change its scope, or move the cout inside the loop - that's if you want to print them all):
for (int i = 3 ; PrimeNumbers <=10000; i++)
{
if(prime(i))
{
cout << i << endl;
PrimeNumbers++;
}
}
Also:
for(int j = 2; j < isitprime; j++) ///prime number tester
{
if(isitprime%j == 0) result = false;
}
could be optimized, since (1) you don't need to check all numbers till isitprime, but at most to sqrt(isitprimt) and (2) you only need to check until result is false, at which point you can break out of the loop.
The output isn't strange at all.
cout<<prime<<endl;
You're printing the function pointer of prime here.
You were probably intending to print the variable you create here:
int prime = i;
But this is in the loop scope. In fact, if you compile with warnings enabled, your compiler should tell you that this variable is never used. Also, it's bad practice to give variables in C or C++ the same name as functions (or any other variable in a higher level scope).
Your loop in the main program does not stop correctly because the test variable, PrimeNumbers may not change.
Try:
for (int i = 3; i < 10000; i++)
{
//...
}
Also, because you declared the variable prime inside an if statement, it disappears after the if statement is executed:
if (prime(i))
{
int prime = i; // <-- Declare the variable before the for loop.
//...
The code for finding prime number from nth to 2(1 is neither prime nor composite) is written below, i havent used math.h header file , did something different and surpizingly it works pretty cool....
Code is:
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class prime
{
int a;
int i;
public:
void display();
};
void prime::display()
{
cout<<"Enter the number to see primes less than it till 2";
cin>>a;
int count=0;
for(int j=a;j>=1;j--)
{
for(int i=1;i<=j;i++)
{
if(j%i==0)
{
count++;
}
}
if(count==2)
{
cout<<"\t"<<j;
}
count=0;
}
}
void main()
{
clrscr();
prime k;
k.display();
getch();
}
if you want to find the prime number from 1 to n,hope this will help u.
#include <iostream>
#include <vector>
static bool _isprime (int number)
{
if(number==1)
{
return false;
}
bool flag=true;
if(number==2||number%2!=0)
{
for(int i=2;i<number;i++)
{
if(number%i==0)
{
flag=false;
}
}
}
else flag=false;
return flag;
}
int main (void)
{
using namespace std;
vector<int> primenumber;
cout<<"prime number between 1 and ?"<<endl;
int x=0;
cin>>x;
for(int i=0;i<=x;i++)
{
if(_isprime(i)==true)
{
//cout<<x<<" is a prime number"<<endl;
primenumber.push_back(i);
}
//else cout<<x<<" is not a prime number"<<endl;
}
for(int i=0;i<primenumber.size();i++)
{
cout<<primenumber[i]<<endl;
}
cout<<"the number of prime number is "<<primenumber.size()<<endl;
system("pause");
return 0;
}
I have been working on this for 24 hours now, trying to optimize it. The question is how to find the number of trailing zeroes in factorial of a number in range of 10000000 and 10 million test cases in about 8 secs.
The code is as follows:
#include<iostream>
using namespace std;
int count5(int a){
int b=0;
for(int i=a;i>0;i=i/5){
if(i%15625==0){
b=b+6;
i=i/15625;
}
if(i%3125==0){
b=b+5;
i=i/3125;
}
if(i%625==0){
b=b+4;
i=i/625;
}
if(i%125==0){
b=b+3;
i=i/125;
}
if(i%25==0){
b=b+2;
i=i/25;
}
if(i%5==0){
b++;
}
else
break;
}
return b;
}
int main(){
int l;
int n=0;
cin>>l; //no of test cases taken as input
int *T = new int[l];
for(int i=0;i<l;i++)
cin>>T[i]; //nos taken as input for the same no of test cases
for(int i=0;i<l;i++){
n=0;
for(int j=5;j<=T[i];j=j+5){
n+=count5(j); //no of trailing zeroes calculted
}
cout<<n<<endl; //no for each trialing zero printed
}
delete []T;
}
Please help me by suggesting a new approach, or suggesting some modifications to this one.
Use the following theorem:
If p is a prime, then the highest
power of p which divides n! (n
factorial) is [n/p] + [n/p^2] +
[n/p^3] + ... + [n/p^k], where k is
the largest power of p <= n, and [x] is the integral part of x.
Reference: PlanetMath
The optimal solution runs in O(log N) time, where N is the number you want to find the zeroes for. Use this formula:
Zeroes(N!) = N / 5 + N / 25 + N / 125 + ... + N / 5^k, until a division becomes 0. You can read more on wikipedia.
So for example, in C this would be:
int Zeroes(int N)
{
int ret = 0;
while ( N )
{
ret += N / 5;
N /= 5;
}
return ret;
}
This will run in 8 secs on a sufficiently fast computer. You can probably speed it up by using lookup tables, although I'm not sure how much memory you have available.
Here's another suggestion: don't store the numbers, you don't need them! Calculate the number of zeroes for each number when you read it.
If this is for an online judge, in my experience online judges exaggerate time limits on problems, so you will have to resort to ugly hacks even if you have the right algorithm. One such ugly hack is to not use functions such as cin and scanf, but instead use fread to read a bunch of data at once in a char array, then parse that data (DON'T use sscanf or stringstreams though) and get the numbers out of it. Ugly, but a lot faster usually.
This question is from codechef.
http://www.codechef.com/problems/FCTRL
How about this solution:
#include <stdio.h>
int a[] = {5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625, 48828125, 244140625};
int main()
{
int i, j, l, n, ret = 0, z;
scanf("%d", &z);
for(i = 0; i < z; i++)
{
ret = 0;
scanf("%d", &n);
for(j = 0; j < 12; j++)
{
l = n / a[j];
if(l <= 0)
break;
ret += l;
}
printf("%d\n", ret);
}
return 0;
}
Any optimizations???
Knows this is over 2 years old but here's my code for future reference:
#include <cmath>
#include <cstdio>
inline int read()
{
char temp;
int x=0;
temp=getchar_unlocked();
while(temp<48)temp=getchar_unlocked();
x+=(temp-'0');
temp=getchar_unlocked();
while(temp>=48)
{
x=x*10;
x+=(temp-'0');
temp=getchar_unlocked();
}
return x;
}
int main()
{
int T,x,z;
int pows[]={5,25,125,625,3125,15625,78125,390625,1953125,9765625,48828125,244140625};
T=read();
for(int i=0;i<T;i++)
{
x=read();
z=0;
for(int j=0;j<12 && pows[j]<=x;j++)
z+=x/pows[j];
printf("%d\n",z);
}
return 0;
}
It ran in 0.13s
Here is my accepted solution. Its score is 1.51s, 2.6M. Not the best, but maybe it can help you.
#include <iostream>
using namespace std;
void calculateTrailingZerosOfFactoriel(int testNumber)
{
int numberOfZeros = 0;
while (true)
{
testNumber = testNumber / 5;
if (testNumber > 0)
numberOfZeros += testNumber;
else
break;
}
cout << numberOfZeros << endl;
}
int main()
{
//cout << "Enter number of tests: " << endl;
int t;
cin >> t;
for (int i = 0; i < t; i++)
{
int testNumber;
cin >> testNumber;
calculateTrailingZerosOfFactoriel(testNumber);
}
return 0;
}
#include <cstdio>
int main(void) {
long long int t, n, s, i, j;
scanf("%lld", &t);
while (t--) {
i=1; s=0; j=5;
scanf("%lld", &n);
while (i != 0) {
i = n / j;
s = s + i * (2*j + (i-1) * j) / 2;
j = j * 5;
}
printf("%lld\n", s);
}
return 0;
}
You clearly already know the correct algorithm. The bottleneck in your code is the use of cin/cout. When dealing with very large input, cin is extremely slow compared to scanf.
scanf is also slower than direct methods of reading input such as fread, but using scanf is sufficient for almost all problems on online judges.
This is detailed in the Codechef FAQ, which is probably worth reading first ;)