This is my code for finding prime numbers between two integers. It compiles alright but giving a runtime error SIGXFSZ on codechef.
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n,m;
int t;
cin>>t;
while(t--)
{
cin>>m>>n;
for(long long j=m;j<=n;j++)
for(long long i=2;i<=sqrt(j);i++)
if(j%i==0)
break;
else cout<<j<<"\n";
cout<<"\n";
}
return 0;
}
Seems that you are wrong on logic.
According to my understanding, you are supposed to print the prime numbers between two numbers.
But your code has logical errors.
1) Code doesn't consider 2 and 3 as prime numbers.
Say, m = 1, n = 10. For j = 2, 3, the inner loop won't execute even for the single time. Hence, the output won't be shown to be user.
2) else cout<<j<<"\n"; statement is placed incorrectly as it will lead to prime numbers getting printed multiple times and some composite numbers also.
Example:
For j = 11, this code will print 11 twice (for i = 2, 3).
For j = 15, this code will print 15 once (for i = 2) though it is a composite number.
You've underexplained your problem and underwritten your code. Your program takes two separate inputs: first, the number of trials to perform; second, two numbers indicating the start and stop of an individual trial.
Your code logic is incorrect and incomplete. If you were to use braces consistently, this might be clear. The innermost loop needs to fail on non- prime but only it's failure to break signals a prime, so there can't be one unless the loop completes. The location where you declare a prime is incorrect. To properly deal with this situation requires some sort of flag variable or other fix to emulate labelled loops:
int main() {
int trials;
cin >> trials;
while (trials--)
{
long long start, stop;
cin >> start >> stop;
for (long long number = start; number <= stop; number++)
{
if (number < 2 || (number % 2 == 0 && number != 2))
{
continue;
}
bool prime = true;
for (long long odd = 3; odd * odd <= number; odd += 2)
{
if (number % odd == 0)
{
prime = false;
break;
}
}
if (prime)
{
cout << number << "\n";
}
}
}
return 0;
}
The code takes the approach that it's simplest to deal with even numbers and two as a special case and focus on looping over the odd numbers.
This is basically "exceeded file size", which means that the output file is having size larger than the allowed size.
Please do check the output file size of your program.
Related
I was trying this question.
The prime factors of 13195 are 5, 7, 13 and 29.What is the largest prime factor of the number 600851475143 ?
And I had written the following code:
#include<iostream>
#define num 600851475143
using namespace std;
int isprime(unsigned long long int n)
{
unsigned long long int c=0;
for(unsigned long long int i=2;i<n;i++)
{
if(n%i==0)
{
c++;
break;
}
}
if(c==0)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
unsigned long long int a,i,n=num;
while(n-- && n>1)
{
if(isprime(n)==1 && num%n==0)
{
cout<<n;
break;
}
}
return 0;
}
The problem occurring with the code is it is working for 13195 and other small values. But not getting any output for 600851475143. Can anyone explain why it is not working for large value and also tell the changes that should be made in these to get the correct output.
The below code snippets are from c (but should run quite nice with c++ as well):
#include <stdio.h>
#define uIntPrime unsigned long long int
#define uIntPrimeFormat "llu"
uIntPrime findSmallestPrimeFactor(uIntPrime num)
{
uIntPrime limit = num / 2 + 1;
for(uIntPrime i=2; i<limit; i++)
{
if((num % i) == 0)
{
return i;
}
}
return num;
}
uIntPrime findLargestPrimeFactor(uIntPrime num)
{
uIntPrime largestPrimeFactor = 1; // start with the smallest possible value
while (num > 1) {
uIntPrime primeFactor = findSmallestPrimeFactor(num);
if (primeFactor > largestPrimeFactor) largestPrimeFactor = primeFactor;
num = num / primeFactor;
}
return largestPrimeFactor;
}
How can this work?
(first function:) Counting the numbers up from 2 means you are starting with prime factors on the lower end. (Numbers that are non-prime when counting are just not working out as fraction-less divisors and at the same time their prime number factor components were already probed because they are lower.)
(second function:) If a valid factor is found then the factor is pulled out from the number in question. Thus the search for the now smallest prime in the pulled-out number can repeat. (The conditional might probably be superfluous due to lower numbers are found first anyway - but it might resemble a search pattern you are familiar with - like in a minimum/maximum/other-criteria search. I am now leaving it up to you to proof it right or wrong with testing with your own main routine.)
The stop condition is about having the last factor extracted means dividing the value by itself and getting a value of 1 for num.
(There is for sure still much space for speeding this up!)
I want to build the following program:
The user has to insert a number between 100 and 999 (like 100 < i < 999) and the numbers have to be multiplied among themselves.
Example:
A Valid Input: 178
Corresponding Result: 1*7*8 = 72
I tried to achieve the first part i.e. checking for the number given as input to be within 100 and 999 in the two ways below, but my approach isn't said to be elegant:
#include <stdio.h>
int main()
{
char n[4];
scanf("%s", n);
printf("%d\n", (n[0]-'0')*(n[1]-'0')*(n[2]-'0'));
return 0;
}
or
#include<stdio.h>
int main()
{
int array[3];
scanf("%1d%1d%1d", &array[0],&array[1],&array[2]);
for ( int i=0; i<3; i++) {
printf("%d\n", array[i]);
}
return 0;
}
Are they any better ways to achieve the same?
I'm looking for a C++ solution.
You can impose std::cin as a conditional in a while:
int x;
while (std::cin >> x && x>=100 && x <=999)
\\ Do what you want
For multiplying the digits, simply extract each digit by getting its remainder when divided by 10, multiply that with the current product (set a variable, with inital value 1) then divide by 10 subsequently in a loop till you get the product of all digits. For example, create a function which returns the product of digits of a number:
int digitproduct(int x)
{ int product = 1;
while (x != 0)
{
product *= (n % 10);
x /= 10;
}
return product;
}
Call that inside the while:
int x;
while (std::cin >> x && x>=100 && x <=999)
{ cout<< digitproduct(x);
break;
}
People may say, your solution isn't elegant, because it does not easily scales if you may want to add more digest or remove some.
The first one will also have a buffer overflow as soon the user enters more than 4 characters!
But out of my option I like the second one quite much, because it shows a much better understanding of C than just reading the number via int n; std::cin >> n;, validating it, and then calculating the result.
But there is a small flaw as well, you need to check the return value of scanf in order to detect if a number has been successfully parsed or not.
int res = scanf("%1d%1d%1d", &array[0],&array[1],&array[2]);
if(res != 3) {
printf("Invalid number format. Expected a three digit number, but got %d", res);
return 0;
}
More elegant solution will be to obtain the number as an integer and then decompose it to the single digits with division and modulo operations.
This greatly increases the ability to validate the input number and knowing how to decompose the integer may be useful if the number is not given as a string, but from other parts of the program as a number.
Sample code:
#include <stdio.h>
int main() {
int number;
scanf("%d", &number);
if(number > 999 || number < 100) {
printf("Number not in range\n");
return -1;
}
printf("%d\n",
(number / 100) * // hundreds digit
(number / 10 % 10) * // tens digit
(number % 10) // units digit
);
return 0;
}
I'm writing a program for finding whether a given number is an Armstrong Number:
int main()
{
int n,rem,sum=0;
cout<<"Enter the Number for checking"<<endl;
cin>>n;
while(n!=0)
{
rem=n%10;
sum=sum+(rem*rem*rem);
n=n/10;
}
if(sum==n)
{
cout<<"Armstrong Number"<<endl;
}
else
{
cout<<"It's not a armstrong number";
}
return 0;
}
When I run it, it always reports "It's not a armstrong number", regardless of input.
I changed the code as follows, and got the correct result. But I don't understand why I need to assign input to n1 and do the operation - why can't I directly do the operation with n?
int main()
{
int n,rem,sum=0,n1;
cout<<"Enter the Number for checking"<<endl;
cin>>n;
n1=n;
while(n1!=0)
{
rem=n1%10;
sum=sum+(rem*rem*rem);
n1=n1/10;
}
if(sum==n)
{
cout<<"Armstrong Number"<<endl;
}
else
{
cout<<"It's not a armstrong number";
}
return 0;
}
In the line if (sum==n) your program compares sum and n. In the second program n is initial number entered by user. But in the first program n==0 (see the loop above it).
So, in the first program the check if (sum==n) works as if (sum==0). But value of sum is never 0 (except user entered 0). So, first program always returns "It's not a armstrong number".
And about style: It is much better to use functions instead of putting the whole logic into one main() function. For instance, you can create a function for calculation of the intermediate sum for cheching of Armstrong Number:
int getSumOfCubesOfDigits(int n)
{
int sum = 0;
while (n)
{
const int rem = n % 10;
sum += rem * rem * rem;
n = n / 10;
}
}
In this case your program will be much simpler and it will be hard to make the mistake you have in the first program of your question:
int main()
{
int n;
cout << "Enter the Number for checking" << endl;
cin >> n;
if(getSumOfCubesOfDigits(n) == n)
cout<<"Armstrong Number"<<endl;
else
cout<<"It's not a armstrong number";
return 0;
}
In the first program, the original number is entered into 'n'. The only problem in your logic is, you forgot that by the time you exit from the while loop, 'n' will no longer be your original number since you are repeatedly doing n=n/10, and hence 'sum==n' never satisfies even for an Armstrong number.
So before you enter the while loop, save the original number into another variable, say n1 (as done in the second program you provided), and only use n1 for operations, ie, n1=n1/10. Leave n alone so that, in the end 'n' will still contain the original number, which you can finally compare with 'sum' to find your answer.
Which number do you compare ? , in first program in while loop , n value is changed ( in this variable you get the input) and finally check with sum == n , so it always get condition fail.
So temp (n1) variable is required , to compare the final result
Your code is different in the second code block, you are still testing if sum=n.
In the second code block, if you tested if(sum=n1), I would suspect it would work the same.
I got this solution for finding an Armstrong Numbers
int main() {
for (int i=10; i<=9999; i++) {
int k = i,z = 1, s = 0, n = i;
while ((k/=10) > 0) z++;
for (int t = z; t; t--, n/=10) {
s += pow(n % 10, z);
}
if (i == s) cout << i << endl;
}
return 0;
}
I am working on a program in which I must print out the number of primes, including 1 and 239, from 1 - 239 ( I know one and or two may not be prime numbers, but we will consider them as such for this program) It must be a pretty simple program because we have only gone over some basics. So far my code is as such, which seems like decent logical flow to me, but doesnt produce output.
#include <iostream>
using namespace std;
int main()
{
int x;
int n = 1;
int y = 1;
int i = 0;
while (n<=239)
{x = n % y;
if (x = 0)
i++;
if (y < n)
y++;
n++;
while (i == 2)
cout << n;
}
return 0;
}
The way I want this to work is to take n, as long as n is 239 or less, and preform modulus division with every number from 1 leading up to n. Every time a number y goes evenly into n, a counter will be increased by 1. if the counter is equal to 2, then the number is prime and we print it to the screen. Any help would be so greatly appreciated. Thanks
std::cout << std::to_string(2) << std::endl;
for (unsigned int i = 3; i<240; i += 2) {
unsigned int j = 3;
int sq = sqrt(i);
for (; j <= sq; j += 2) if (!(i%j)) break;
if (j>sq) std::cout << std::to_string(i) << std::endl;
}
first of all, the prime definition: A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
so you can skip all the even numbers (and hence ... i+=2).
Moreover no point to try to divide for a number greater than sqrt(i), because then it will have a divisor less than sqrt(i) and the code finds that and move to the next number.
Considering only odd numbers, means that we can skip even numbers as divisors (hence ... j+=2).
In your code there are clearly beginner errors, like (x = 0) instead of x==0. but also the logic doesn't convince. I agree with #NathanOliver, you need to learn to use a debugger to find all the errors. For the rest, good luck with the studies.
lets start with common errors:
first you want to take input from user using cin
cin>>n; // write it before starting your while loop
then,
if (x = 0)
should be:
if (x == 0)
change your second while loop to:
while (i == 2){
cout << n;
i++;
}
I'm pretty new to programming and so I"m making this program in C++ that will take a number and find it's prime factors, which works great! Unless it's too big for an int variable. Now then I tried to change all of the int variables to long long variables so it wouldn't matter, but this doesn't seem to fix the problem. The program is as follows:
#include <iostream>
using namespace std;
bool prime (long long recievedvalue) { //starts a function that returns a boolean with parameters being a factor from a number
long long j =1;
long long remainderprime = 0;
bool ended = false;
while (ended == false){ //runs loop while primality is undetermined
if (recievedvalue == 1){ //if the recieved value is a 1 it isn't prime
//not prime
return false;
break; // breaks loop
}
remainderprime=recievedvalue%j; //gives a remainder for testing
if ((remainderprime==0 && j>2) && (j!=recievedvalue || j == 4)){ //shows under which conditions it isn't prime
ended=true;
//not prime
return false;
}
else if (j==1){
j++;
}
else if ( recievedvalue==2 || j==recievedvalue ){ // shows what conditions it is prime
ended = true;
//prime
return true;
}
else {
j++;
}
}
}
long long multiple(long long tbfactor){ //factors and then checks to see if factors are prime, then adds all prime factors together
//parameter is number to be factored
long long sum = 0;
bool primetest = false;
long long remainderfact;
long long i=1;
while (i<=tbfactor){ //checks if a i is a factor of tbfactor
remainderfact=tbfactor%i;
if (remainderfact==0){ //if it is a factor it checks if it is a prime
primetest = prime(i);
}
if (primetest ==true){ //if it is prime it add that to the sum
sum += i;
primetest=false;
}
i++;
}
return sum;
}
int main()
{
long long input;
long long output;
cout << "Enter a number > 0 to find the sum of all it's prime factors: ";
cin >> input;
if (input == 0 || input <= 0){
cout << "The number you entered was too small."<< endl << "Enter number a number to find the sum of all it's prime factors: ";
cin >> input;
}
output = multiple(input);
cout << output << endl << "finished";
return 0;
}
Now then to be sure, the problem does the same thing whether or not it's a int or not. Also like I said I"m new to programming, and C for that matter so I look forward to your easily understandable replies. :)
I'm willing to be that your program IS running. I'm sure that someone is going to pop on and give you the answer in a heartbeat, but I'm hoping that it doesn't happen so that you get to experience the same thing that I did when I ran into the problem YEARS ago.
Do this: start with 1, and work up from there using powers of 2 (1, 2, 4, 8, 16, etc.) and just keep going, doubling the input number each time. When does it "stop running?" Does it get progressively slower?
Please comment back on my post or on your own, or edit your own, or post an answer, whatever it is you're allowed to do with only 56 rep. If the community will allow it (and of course I would like the community to further the lesson), I'd like to gently push you to the answer through a series of back-and-forth steps feedback rather than the typical fashion, since this is an obvious unique learning opportunity.
If you are trying to find if a number is a prime or not, here is a fast solution,
#include <iostream>
using namespace std;
#define ullong unsigned long long
bool prime (ullong x)
{
if(x <= 1)
return false;
ullong s = (ullong)sqrt(x);
for(ullong i=2;i<=s;i++)
if(x%i == 0)
return false;
return true;
}