Program aborts - Prime factor of numbers read from a file - c++

This code decomposes a number into its prime factors.
The numbers are taken from a file. The first number from the file represents the number of elements in it, the numbers are from the interval [1, 10^18].
The problem with the code is that after reading and decomposing some numbers it stops. It is intended to decompose somewhere between 100 and 1000 numbers from which at least half are bigger than 10^9.
I suspect that the stack overflows, but I am not 100% sure. I would like to hear some suggestions in order to fix this memory allocation problem.
Thank you.
#include <iostream>
#include <stdio.h>
using namespace std;
void print_recurenta(int a,int i)
{
if((a==1)||(i>a))
return;
if(a%i==0)
{
printf("%d ",i);
a=a/i;
print_recurenta(a,i);
}
else
{
i++;
print_recurenta(a,i);
}
}
void factor_printf(int nr)
{
printf("\n%ld ",nr);
int i=2;
print_recurenta(nr,i);
}
int main()
{
int numere;
int nr=0;
FILE* f=fopen("input.txt","r");
if(f==0)
return -1;
fscanf(f,"%d",&numere);
while(fscanf(f,"%d",&nr)!=EOF)
{
fscanf(f,"%d",&nr);
factor_printf(nr);
}
return 0;
}

This problem CAN be solved recursively if we look for the next factor in a loop:
void print_recurenta(__int64 a, __int64 i)
{
if (a == 1)
return;
if (i*i > a)
{
printf("%llu ", a);
return;
}
if (a%i == 0)
{
printf("%llu ", i);
a = a / i;
}
else
{
for (++i; i*i < a && (a%i != 0); ++i)
;
}
print_recurenta(a, i);
}

Related

C++ Gapful Numbers Crashing

I was doing this program in which I am supossed to print gapful numbers all the way up to a specific value. The operations are correct, however, for some reason after printing a couple of values the program crashes, what can I do to fix this problem?
Here's my code:
#include<math.h>
#include<stdlib.h>
using namespace std;
void gapful(int);
bool gapCheck(int);
int main(){
int n;
cout<<"Enter a top number: ";
cin>>n;
gapful(n);
system("pause");
return 0;
}
void gapful(int og){
for(int i=0; i<=og; i++){
fflush(stdin);
if(gapCheck(i)){
cout<<i<<" ";
}
}
}
bool gapCheck(int n){
int digits=0;
int n_save,n1,n2,n3;
if(n<100){
return false;
}
else{
n_save=n;
while(n>10){
n/=10;
digits++;
}
digits++;
n=n_save;
n1=n/pow(10, digits);
n2=n%10;
n3=n1*10 + n2;
if(n%n3 == 0){
return true;
}
else{
return false;
}
}
}
I'm open to any suggestions and comments, thank you. :)
For n == 110, you compute digits == 3. Then n1 == 110 / 1000 == 0, n2 == 110 % 10 == 0, n3 == 0*10 + 0 == 0, and finally n%n3 exhibits undefined behavior by way of division by zero.
You would benefit from more functions. Breaking things down into minimal blocks of code which represent a single purpose makes debugging code much easier. You need to ask yourself, what is a gapful number. It is a number that is evenly divisible by its first and last digit. So, what do we need to solve this?
We need to know how many digits a number has.
We need to know the first digit and the last digit of the number.
So start out by creating a function to resolve those problems. Then, you would have an easier time figuring out the final solution.
#include<math.h>
#include <iostream>
using namespace std;
void gapful(int);
bool gapCheck(int);
int getDigits(int);
int digitAt(int,int);
int main(){
int n;
cout<<"Enter a top number: " << endl;
cin>>n;
gapful(n);
return 0;
}
void gapful(int og){
for(int i=1; i<=og; ++i){
if(gapCheck(i)){
cout<<i << '-' <<endl;
}
}
}
int getDigits(int number) {
int digitCount = 0;
while (number >= 10) {
++digitCount;
number /= 10;
}
return ++digitCount;
}
int digitAt(int number,int digit) {
int numOfDigits = getDigits(number);
int curDigit = 0;
if (digit >=1 && digit <= numOfDigits) { //Verify digit is in range
while (numOfDigits != digit) { //Count back to the digit requested
number /=10;
numOfDigits -=1;
}
curDigit = number%10; //Get the current digit to be returned.
} else {
throw "Digit requested is out of range!";
}
return curDigit;
}
bool gapCheck(int n){
int digitsN = getDigits(n);
if (digitsN < 3) { //Return false if less than 3 digits. Single digits do not apply and doubles result in themselves.
return false;
}
int first = digitAt(n,1) * 10; //Get the first number in the 10s place
int second = digitAt(n,digitsN); //Get the second number
int total = first + second; //Add them
return n % total == 0; //Return whether it evenly divides
}

When i recurse the following code on function prime the program crashes what is wrong in my code?

Whenever I try to recurse in the function prime, my program crashes at that step. I think the problem is passing the function small as a recursion. What am I doing wrong?
#include <iostream>
using namespace std;
int smallest(int n) {
for( int x = 2 ; x <= n/2 ; x++){
if (n%x==0) {
return x;
}
else {
return 0;
}
}
}
int prime(int n, int(*small)(int)) {
int factor;
if (n == 1){
return 0;
}
else {
factor = n % small(n);
cout << small(n) << endl;
return prime(factor , small);
}
}
int main() {
prime(50 , &smallest);
return 0;
}
As the comments point out, when small returns 0, you continue recursing when you shouldn't. This can be solved with a small update to your base case:
if (n <= 1){
return 0 ;
}
Furthermore, it's worth pointing out that as it stands, your prime function will never call itself more than once. When you call smallest, you are guaranteed to get a prime number!

Print all prime number lower than n in C++ ( file crash )

I wrote a C++ program that prints all prime numbers lower than n, but the program keeps crashing while executing.
#include <iostream>
using namespace std;
bool premier(int x) {
int i = 2;
while (i < x) {
if (x % i == 0)
return false;
i++;
}
return true;
}
int main() {
int n;
int i = 0;
cout << "entrer un entier n : ";
cin >> n;
while (i < n) {
if (n % i == 0 && premier(i))
cout << i;
i++;
}
;
}
As Igor pointed out, i is zero the first time when n%i is done. Since you want only prime numbers and the smallest prime number is 2, I suggest you initialise i to 2 instead of 0.
You want to print all prime numbers less than n and has a function to check primality already.
Just
while (i < n){
if ( premier(i) == true )
cout<<i;
i++;
}
And while printing, add a some character to separate the numbers inorder to be able to distinguish them like
cout<<i<<endl;
P.S: I think you call this a C++ program. Not a script.
Edit: This might interest you.

How to find prime factors of a number in c++?

I am attempting project euler question number 3, and I don't get the desired result. My logic:
List all the factors of the number 13195 and save them in an array.
Check if each number in the array is a prime.
If the number is found to be prime save it in an other array.
display the contents of the second array.
Hope it contains only prime factors.
RESULT: The first array contains all the factors as expected, The second I think duplicates the first array or slips in some non-primes, Please help! :)
My code:
#include <iostream>
using namespace std;
long int x,y=2;
long int number=13195;
long int f[1000000],ff[1000000];
int st=1;
int open=0;
int open2=0;
int a=0;
bool isprime;
int main()
{
for(x=1;x<=number;x++)
{
if(number%x==0)
{
f[a] = x;
a++;
}
}
while(st<=16)
{
while(y<f[st])
{
if(f[st]%y==0 && f[st]!=y)
{
break;
}
else if(f[st]%y!=0 && f[st!=y])
{
ff[open] = f[st];
}
y++;
}
open++;
st++;
}
for(open2=0;open2<open;open2++)
{
cout<<ff[open2]<<" is a prime factor of "<<number<<"\n";
}
return 0;
}
using this for finding the prime works:
while(st<=a){
int k = f[open];
for(int i=2;i<k;i++)
{
if(k%i==0)
{
isprime = false;
break;
}
else if(f[open]!=0 && f[open]%i!=0 && f[open]!=i)
{
isprime =true;
}
}
if(isprime==true)
{
ff[st] = k;
open3++;
isprime = false;
}
open++;
st++;
}
cout<<"The primes of them are "<<open3<<"."<<"\n";
cout<<"Press RETURN to show them."<<"\n";
cin.get();
for(open2=0;open2<=open3;open2++)
{
cout<<ff[open2]<<" is a prime factor of "<<number<<"."<<"\n";
}
Why You Don't Try
for(x=1;x<=number;x++)
{
if(number%x==0 && isPrime(x))
{
f[a] = x;
a++;
}
}
..
..
int isPrime(int x)
{
for(int i=2;i<=x/2;i++)
{
if(x%i==0)
return 0;
}
return 1;
}
At least:
else if(f[st]%y!=0 && f[st!=y])
should be
else if(f[st]%y!=0 && f[st]!=y)
In the first way, you are trying to always access f[0] or f[1] by doing f[st!=y].

Recursive/iterative functions

I'm having a bit of a hard time creating a function, using iteration and recursion to find the sum of all even integers between 1 and the number the user inputs. The program guidelines require a function to solve this three ways:
a formula
iteration
recursion
This is what I have so far:
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
void formulaEvenSum(int num, int& evenSum)
{
evenSum = num / 2 * (num / 2 + 1);
return;
}
void loopEvenSum(int num, int& evenSum2)
{
}
int main()
{
int num, evenSum, evenSum2;
cout << "Program to compute sum of even integers from 1 to num.";
cout << endl << endl;
cout << "Enter a positive integer (or 0 to exit): ";
cin >> num;
formulaEvenSum(num, evenSum);
loopEvenSum(num, evenSum2);
cout << "Formula result = " << evenSum << endl;
cout << "Iterative result = " << evenSum2 << endl;
system("PAUSE");
return 0;
}
Using iteration to find the sum of even number is as given below.
void loopEvenSum(int num, int &evenSum2)
{
evenSum2=0;
for (i=2;i<=num;i++)
{
if(i%2==0)
evenSum2+=i;
}
}
The following code though not the most efficient can give you an idea how to write a recursive function.
void recursiveEvenSum(int num,int &evenSum3,int counter)
{
if(counter==1)
evenSum3=0;
if(counter>num)
return;
if(counter%2==0)
evenSum3+=counter;
recursiveEvenSum(num,evenSum3,counter+1);
}
Now you can call recursiveEvenSum(...) as
int evenSum3;
recursiveEvenSum(num,evenSum3,1);
You should be able to build an iterative solution using a for loop without too much problem.
A recursive solution might take the form:
f(a)
if(a>0)
return a+f(a-1)
else
return 0
f(user_input)
You have to differentiate between a case where you "dive deeper" and one wherein you provide an answer which doesn't affect the total, but begins the climb out of the recursion (though there are other ways to end it).
An alternative solution is a form:
f(a,sum,total)
if(a<=total)
return f(a+1,sum+a,total)
else
return sum
f(0,0,user_input)
The advantage of this second method is that some languages are able to recognise and optimize for what's known as "tail recursion". You'll see in the first recursive form that it's necessary to store an intermediate result for each level of recursion, but this is not necessary in the second form as all the information needed to return the final answer is passed along each time.
Hope this helps!
I think this does it Don't forget to initialize the value of evenSum1, evenSum2 and evenSum3 to 0 before calling the functions
void loopEvenSum(int num, int& evenSum2)
{
for(int i = num; i > 1; i--)
if(i%2 == 0)
evenSum2+=i;
}
void RecursiveEvenSum(int num, int & evenSum3)
{
if(num == 2)
{
evenSum3 + num;
return;
}
else
{
if(num%2 == 0)
evenSum3+=num;
num--;
RecursiveEvenSum(num, evenSum3);
}
}
void loopEvenSum(int num, int& evenSum2)
{
eventSum2 = 0;
for(int i = 1 ; i <= num; i++){
(i%2 == 0) eventSum += i;
}
}
void recurEvenSum(int num, int& evenSum3)
{
if(num == 1) return;
else if(num % 2 == 0) {
eventSum3 += num;
recurEvenSum(num-1, eventSum3);
}
else recurEvenSum(num-1, eventSum3);
}
btw, you have to initialize evenSum to 0 before calling methods.
the recursive method can be much simpler if you return int instead of void
void iterEvenSum(int num, int& evenSum2)
{
evenSum2 = 0;
if (num < 2) return;
for (int i = 0; i <= num; i+=2)
evenSum2 += i;
}
int recurEvenSum(int num)
{
if (num < 0) return 0;
if (num < 4) return 2;
return num - num%2 + recurEvenSum(num-2);
}
To get the sum of all numbers divisible by two in the set [1,num] by using an iterative approach, you can loop through all numbers in that range, starting from num until you reach 2, and add the number of the current iteration to the total sum, if this is divisible by two.
Please note that you have to assign zero to evenSum2 before starting the loop, otherwise the result will not be the same of formulaEvenSum().
void loopEvenSum(int num, int& evenSum2)
{
assert(num > 0);
evenSum2 = 0;
for (int i=num; i>=2; --i) {
if (0 == (i % 2)) {
evenSum2 += i;
}
}
}
To get the same result by using a recursive approach, instead of passing by reference the variable that will hold the sum, i suggest you to return the sum at each call; otherwise you'll need to hold a counter of the current recursion or, even worse, you'll need to set the sum to zero in the caller before starting the recursion.
int recursiveEventSum(int num)
{
assert(num > 0);
if (num == 1) {
return 0;
} else {
return ((num % 2) ? 0 : num) + recursiveEventSum(num-1);
}
}
Please note that, since you get an even number only if you subtract two (not one) from an even number, you could do optimisation by iterating only on those numbers, plus eventually, the first iteration if num was odd.