How to print the nth number of the series? - c++

I am trying to print the nth number of the series
2,23,235,2357,235711,23571113...
but i am not getting the right output after n=3.
At n=3 it's giving 234 which is wrong
#include<stdio.h>
#include<math.h>
main()
{
unsigned int t, n, p, i, j, d;
int s;
scanf("%d", &t);
if (t <= 10)
{
while (t != 0)
{
scanf("%d", &n);
p = n;
j = 2;
s = 0;
while (p > 0)
{
d = prime(j);
// printf("%d",d);
if (d == 1)
{
s = s + j * pow(10, p - 1);
p--;
j++;
}
else
j++;
}
printf("%d", s);
t--;
}
}
}
int prime(int num)
{
int i, flag = 1, n;
// n=sqrt(num);
for (i = 2; (i <= num / 2) && (flag == 1); i++)
{
if (num % i == 0)
flag = 0;
}
if (flag == 0)
return 0;
else
return 1;
}
I am trying to generate a prime number after each iteration.

So you're generating primes and want to output strings of the concatenated primes.
Write a function filling an array with the first n primes. That's easy.
Then you write an output function like:
for (i = 0; i < n; ++i) {
for (j = 0; j <= i; ++j) {
printf("%d", arr[j]);
}
printf("\n"); /* or any other separator */
}
No trouble any more with large numbers, until you reach primes in the order of magnitude of a billion.

In some low-quality C implementations, the pow function does not return a correct result even when the mathematical result is exactly representable in the floating-point format. E.g., pow(10, 2) may return 99.9999999999999857891452847979962825775146484375 instead of 100.
When a floating-point value that is not an integer is assigned to an integer object, the value is converted to an integer by truncation. Thus, for example, 234.9999847412109375 would become 234.
Generally, you should avoid using floating-point functions such as pow for integer arithmetic. However, for reasonably small values where you know the result of pow should be exactly an integer, you can correct the result by using round: round(pow(10, p - 1)).

Without using any extra space and inbuilt function !
#include<stdio.h>
int isPrime(int p)
{
int i;
for(i=2;i*i<=p;i++)
if(p%i==0)
return 0;
return 1;
}
int main()
{
int n=10,count=0,p=2;
while(count<n)
{
if(isPrime(p))
{
printf("%d",p);
count++;
}
p++;
}
}
even you can get rid of "count" variable by decrementing 'n'. and optimize this code by considering the fact that even numbers are not prime number (or all prime numbers are of the form of 6n+1 or 6n-1 ).

Related

Are my if-conditions correct to sum up the even fibonacci numbers up to 4 million?

Starting from 1 and 2, compute the sum of all even fibonacci numbers (while these numbers are smaller or equal to 4 million)
I am trying to sum all even fibonacci numbers up to 4e6, but it doesn't give me anywhere the right result, and I don't understand where I've messed up. In my mind, the conditions for the if are correct.
My fibonacci() function, and my function to sum the even numbers up, is below.
int fibonacci(int k) //compute the k-th fibonacci number (with EulerProject formula)
{
if (k == 1 || k == 2)
{
return k;
}
{
return (fibonacci(k-1)+ fibonacci(k-2));
}
}
int evenfibonacci()
{
int result = 0;
for (int k = 1; fibonacci(k)<=4e6;) {
if (fibonacci(k)%2 == 0 ) {
result += fibonacci(k);
k++;
} else {
k++;
}
}
}
evenfibonacci() is declared as returning an int value, but does not actually return anything, which is undefined behavior. Thus, the return value is always indeterminate, it ends up returning random garbage, which is why you never get a good result.
You need to add a return statement, eg:
int evenfibonacci()
{
int result = 0;
for (int k = 1; fibonacci(k) <= 4e6; ++k) {
if (fibonacci(k) % 2 == 0) {
result += fibonacci(k);
}
}
return result; // <-- ADD THIS
}
Online Demo
That being said, calling fibonacci(k) 3 times per loop iteration is very inefficient, calculating the same values over and over, especially for higher values of k. You should call it only 1 time per loop, eg:
int evenfibonacci()
{
int result = 0;
for (int k = 1; k <= 33; ++k) {
int value = fibonacci(k);
if (value % 2 == 0) {
result += value;
}
}
return result;
}
Online Demo
Of course, a better solution would be to get rid of fibonacci() altogether, and instead use an iterative approach to calculating only new values per iteration, eg:
int evenfibonacci()
{
int result = 2;
int last[2] = {1, 2};
for (int k = 3; k <= 33; ++k) {
int value = last[0] + last[1];
if (value % 2 == 0) {
result += value;
}
last[0] = last[1];
last[1] = value;
}
return result;
}
Online Demo

Efficient way of finding number of divisors of a number n less than k

I have done this :-
int divisors(int div, int i) {
int ans = 0;
for (int j = 1; j * j <= div; j++) {
if (div % j == 0) {
if (div / j == j && j < i)ans++;
else {
if (j < i && div / j < i) {
ans += 2;
}
else if (j < i) {
ans += 1;
}
else {
break;
}
}
}
}
return ans;
}
however this takes O(sqrt(div)) time, i there a way to optimize this?
You haven't said what you will do with this function. If you are going to calculate the number of divisors (less than a limit) for just a few numbers then the approach of using a function like the one you present could well be the best way.
On the other hand if you want to compute this for all numbers (between some limits perhaps) then a better approach might be to calculate this rather like the sieve of Aritosthenes. That is you loop over the divisors d in range, and for each d add 1 to the count for d, 2d, ... these being the only numbers that can be divided by d.
So something along the lines of
void compute( int maxn, int maxd, int* counts)
{ memset( counts, 0, maxn *sizeof *counts);
for( int d=1; d<maxd; ++d)
{ for( int n=d; n<maxn; n+=d)
{ counts[n] += 1;
}
}
}
After calling this counts[n] will hold the number of divisors less than maxd for each n 0,..maxn-1. Note that there are no divisions or modulus operations at all in the code above; these are often much slower than other arithmetic operations.
You cannot go lower than O(sqrt(N)) because in the worst case you take k = N, that time you'll have to traverse till sqrt(N)

SPOJ PRIME1 Prime Generator: Wrong Answer?

Doing this question on SPOJ, trying to implement a sieve and a segmented sieve to get the desired primes. My code is as follows:
//Prime Generator
#include <iostream>
#include <math.h>
#include <cstdio>
using namespace std;
int main() {
//traditional sieve
int squareRoot = sqrt(1000000000);
//printf("%d\n\n", squareRoot);
bool primeList[squareRoot] = {false}; //all primes are marked as true, composite is false
//make entire array true
for (int i = 1; i < squareRoot; i++){
primeList[i] = true;
}
//traditional sieve to find primes first
for (int i = 2; i <= squareRoot; i++){
for (int j = i*i; j <= squareRoot; j+=i){
//composites are marked as false
primeList[j - 1] = false;
}
}
//segmented sieve + output
int a;
scanf("%d", &a);
while (a > 0){
int m, n;
scanf("%d%d", &m, &n);
//if lower than this range, then we can just output the primes we already computed
if (n <= squareRoot){
for (int i = m; i <= n; i++){
if (primeList[i - 1] == true){
printf("%d\n", i);
}
}
printf("\n");
}
//it is beyond this range, so we need to segment sieve
else {
int upperLimit = sqrt(n); //highest we need to divide by
int diff = n - m;
bool myPrimes[diff + 1];
for (int i = 0; i <= diff; i++){
myPrimes[i] = true;
}
for (int i = 2; i <= upperLimit; i++){
if (primeList[i - 1] == true){
int lowest = m/i * i;
while (lowest < m){
lowest += i;
}
while (lowest <= n){
myPrimes[lowest - m] = false;
lowest += i;
}
}
}
for (int i = m; i <= n; i++){
if (myPrimes[i - m] == true){
printf("%d\n", i);
}
}
printf("\n");
}
a--;
}
}
The basic logic I'm trying to do is:
First do a sieve of Eratosthenes to generate all the primes up to the sqrt of 10^9, since 10^9 is the upper limit of n.
If n is below sqrt(10^9), then I do not calculate anything new, just output the appropriate primes from (1).
If n is above sqrt(10^9), then I first calculate sqrt(n), which is the largest number we'd need, as any number bigger would not be divisible in the range [m, n].
Then I'd do the actual sieve, starting from 2, and trying to mark as false all numbers that are a multiple of a prime. I do 'lowest = m/i * i' to get the number that is the closest to m, where lowest <= m. If it is lower than m, then I add until it is just above m. I.E. if m==125 and n == 200, then 125/2 = 62, 62*2 = 124. 124+2 == 126, which would be the first number that is a multiple of 2 in the series [125,200].
Then we output any numbers that have no been marked false.
My issue is it seems my algorithm is correct (to me). I'm more than certain my first sieve works, but it seems that it might falter at generating primes larger than sqrt(10^9). However, from my testing it seems it does generate all the primes (and only primes). Is my algorithm to generate primes too uncertain? Is it a one-off issue with rounding?
My guess is that the error comes from
for (int i = 2; i <= upperLimit; i++){
if (primeList[i - 1] == true){
int lowest = m/i * i;
while (lowest < m){
lowest += i;
}
while (lowest <= n){
myPrimes[lowest - m] = false;
lowest += i;
}
}
}
But I can't tell where. Any tips or pointers would be welcome!
I got the mistake , its in the second case where you are defining myPrimes[diff] = {true} . But think of the where the time when input is like
m = 1 and n > sqrt(1000000000) then it would give 1 as a prime number.
Hope that would make accept you answer.

Digit-increasing number test

A number is called digit-increasing if it is equal n + nn + nnn + ... for some digit n between 1 and 9. For example 24 is digit-increasing because it equals 2 + 22 (here n = 2).
Actually, a friend of mine asked me this question and i am stuck thinking about it but couldn't find the exact solution so far. Can anyone help ? I needed the function that returns true if it is digit-increasing else false.
There are only relatively few numbers with this property: Within the range of unsigned long long (64 bits), there are only 172 digit-increasing numbers.
Therefore, in terms of a practical solution, it makes sense to pre-compute them all and put them in a hash. Here is Python code for that:
# Auxiliary function that generates
# one of the 'nnnn' elements
def digits(digit,times):
result = 0
for i in range(times):
result += digit*(10**i)
return result
# Pre-computing a hash of digit-increasing
# numbers:
IncDig = {}
for i in range(1,30):
for j in range(1,10):
number = reduce(lambda x,y:x+y,[digits(j,k) for k in range(1,i+1)])
IncDig[number] = None
Then the actual checking function is just a look-up in the hash:
def IncDigCheck(number):
return (number in IncDig)
This is virtually O(1), and the time and space taken for the pre-calculation is minimal, because there are only 9 distinct digits (zero doesn't count), hence only K*9 combinations of type n + nn + ... for a sum of length K.
General representation is:
n + (n*10 + n) + (n*100+n)...
If number look like sum of same digits then any digit can be represented as
(1+111+...) * base_digit
. Assuming this we can use simple algorithm:
bool isDigitIncreasing(const int num)
{
int n = 1;
int sum = 1; //value to increase n
while (n <= num) {
//if num is (111...) * base_digit and base_digit is < 10
if (num % n == 0 && n * 10 > num) return true;
sum = sum * 10 + 1; //N*10+N where n is 1 as was assumed
n += sum; //next step
}
return false;
}
Simple exhaustive search will work.
def is_digit_increasing_number(x):
# n = 1, 1+11, 1+11+111, ...
n = 1
i = 1
while n <= x:
if x % n == 0 and n * 10 > x:
return True
i += 1
n = n * 10 + i
return False
Simplest possible way is do the addition (bottom-up), I'll use simple for loop:
List<int> numbersSum = new List<int>{1,2,3,4,5,6,7,8,9};
List<int> lastNumber = new List<int>{1,2,3,4,5,6,7,8,9};
for(int i=0;i<= lg n + 1;i++)
{
for(int j=0;j<9;j++)
{
if(list[j] < n)
{
var lastNumberJ = lastNumber[j]*10+j+1;
list[j] += lastNumberJ; // add numbers to see will be same as n.
if (list[j] == n)
return j+1;
lastNumber[j] = lastNumberJ;
}
}
}
return -1;
The important part is you just need at most log n iteration and also you can return sooner if all numbers are bigger than given number, this is O(log n) algorithm.
Here is a python code.The basic logic here is that a digit increasing number if divided by a specific number between 1-9 gives a digit increasing number made of only ones.All the digit increasing numbers of 1 follow a specific pattern ie 12345678...
import sys
for n in range(1,10):
a=1
if k%n!=0:
a=0
else:
g=str(k/n)
j=int(g[0])
for i in range(1,len(g)):
if int(g[i])==j+1:
j=int(g[i])
else:
a=0
break
if a==1:
print "Yes,it is a digit increasing number"
sys.exit(0)
print "No,it is not a digit increasing number"
I have done in this way. Check out once.
int sum = 0, count =0;
bool flag = false;
public bool isDigitIncreasing(int input_number)
{
int n= get_number_of_digit(input_number); // Gets number of digits
int sum = 0;
for(int i=0;i<n;i++)
{
sum = sum*10+1;
count = count + sum;
}
for(int i=1; i<=9;i++)
{
if((input_number)==count*i)
{
flag = true;
break;
}
else
flag = false;
}
return flag;
}
public int get_number_of_digit(int num)
{
int size = 0;
do
{
num = num/10;
size++;
}while(num>0);
return size;
}
Here is the shortest solution
public static int isDigitIncreasing (int n)
{
if(n<10)
{
return 1;
}
for(int i=1;i<=9;i++)
{
int tempsum=i;
int previous=i;
while(tempsum<=n)
{
previous=previous*10 + i;
tempsum=tempsum + previous;
if(tempsum==n)
{
return 1;
}
}
}
return 0;
}
Ambiguitiy: Are the values 1-9 repeating for themselves? (too lazy to google this myself)
If 1-9 are repeating then following should work. If not, and you want the code to work only on values > 10 then you can initialize mult with 10.
int i, mult = 1, result, flag;
for( i=1; i<9; i++ )
{
flag = 0;
while( result < TARGET )
{
result = result+(i*mult);
mult = mult*10;
if( result == TARGET )
{
flag = 1;
break;
}
}
if( flag == 1 )
break;
}
After execution, i must contain the values for which RESULT is a repeating number IF the flag is 1. If flag is zero after execution then the TARGET isn't a repeating number.
I wonder if its possible that a number could be repeating for multiple values, just curious.
Here num is the number and n is the digit
#include<stdio.h>
int f(int num,int n)
{
int d=n;
while(num>0)
{
num-=n;
n=d+n*10;
}
if(num==0)
return 1;
else
return 0;
}
int main()
{
int num;
int n;
int flag;
printf("Enter the number :");
scanf("%d",&num);
printf("Enter the digit :");
scanf("%d",&n);
flag = f(num,n);
if(flag == 1)
printf("It's in n+nn+nnn+...\n");
if(flag ==0)
printf("It's not\n");
return 0;
}
Let d(k) be 1+11+111+...+(11...11) where the last number has k digits. Then d(1)=1, and d(k+1)=10d(k)+k+1.
We want to test if d(k)*i = n, for some k, and for some i=1..9.
If we've computed d(k), then i (if it exists) must be n/d(k). We can check if n/d(k) is correct, by comparing n with ((n/d(k))%10)*d(k). The %10 makes the test fail if i is larger than 9.
This gives us a relatively terse solution: compute subsequent d(k) until they are bigger than n, and at each point check to see if n is a digit-multiple of d(k).
Here's a very lightly code-golfed implementation of that idea:
#include <stdio.h>
int is_digit_increasing(int n) {
for(int d=1,k=1;d<=n;d=d*10+ ++k)if(n==(n/d)%10*d)return 1;
return 0;
}
int main(int argc, char**argv) {
for (int i=0; i<10000; i++) {
if (is_digit_increasing(i)) {
printf("%d\n", i);
}
}
return 0;
}
// Example program
#include <iostream>
#include <string>
int isDigitIncreasingNo(int n) {
if(n<=0)
return 0;
int len = std::to_string(n).length();
int vector1 = 0;
int vector2 = 0;
for(int i=1;i<=len;i++)
vector2 = (vector2*10)+i;
vector1 = vector2/10;
if(n % vector2 == 0 && (n / vector2)<=9 )
return 1;
if(n % vector1 == 0 && (n / vector1)<=9 )
return 1;
return 0;
}
int main()
{
for (int i=0; i<10000000; i++) {
if (isDigitIncreasingNo(i)) {
printf("%d\n", i);
}
}
return 0;
}
public boolean isDigitIncreasing(int number)
{
int sum;
int size=calculateNumberOfDigits(number);
for(int i=1;i<=9;i++)
{
sum=0;
int temp=size;
while(temp>=1)
{
for(int j=temp;j<=1;j--)
{
sum=sum+i*(int)Math.pow(10,j-1);
}
temp--;
}
if(sum==number)
{
return true;//Its a digit increasing
}
}
return false;
}
public int calculateNumberOfDigits(int number)
{
int size=0;
do
{
number=number/10;
size++;
}while(size>0);
return size;
}

Finding prime factors

#include <iostream>
using namespace std;
void whosprime(long long x)
{
bool imPrime = true;
for(int i = 1; i <= x; i++)
{
for(int z = 2; z <= x; z++)
{
if((i != z) && (i%z == 0))
{
imPrime = false;
break;
}
}
if(imPrime && x%i == 0)
cout << i << endl;
imPrime = true;
}
}
int main()
{
long long r = 600851475143LL;
whosprime(r);
}
I'm trying to find the prime factors of the number 600851475143 specified by Problem 3 on Project Euler (it asks for the highest prime factor, but I want to find all of them). However, when I try to run this program I don't get any results. Does it have to do with how long my program is taking for such a large number, or even with the number itself?
Also, what are some more efficient methods to solve this problem, and do you have any tips as to how can I steer towards these more elegant solutions as I'm working a problem out?
As always, thank you!
Your algorithm is wrong; you don't need i. Here's pseudocode for integer factorization by trial division:
define factors(n)
z = 2
while (z * z <= n)
if (n % z == 0)
output z
n /= z
else
z++
if n > 1
output n
I'll leave it to you to translate to C++ with the appropriate integer datatypes.
Edit: Fixed comparison (thanks, Harold) and added discussion for Bob John:
The easiest way to understand this is by an example. Consider the factorization of n = 13195. Initially z = 2, but dividing 13195 by 2 leaves a remainder of 1, so the else clause sets z = 3 and we loop. Now n is not divisible by 3, or by 4, but when z = 5 the remainder when dividing 13195 by 5 is zero, so output 5 and divide 13195 by 5 so n = 2639 and z = 5 is unchanged. Now the new n = 2639 is not divisible by 5 or 6, but is divisible by 7, so output 7 and set n = 2639 / 7 = 377. Now we continue with z = 7, and that leaves a remainder, as does division by 8, and 9, and 10, and 11, and 12, but 377 / 13 = 29 with no remainder, so output 13 and set n = 29. At this point z = 13, and z * z = 169, which is larger than 29, so 29 is prime and is the final factor of 13195, so output 29. The complete factorization is 5 * 7 * 13 * 29 = 13195.
There are better algorithms for factoring integers using trial division, and even more powerful algorithms for factoring integers that use techniques other than trial division, but the algorithm shown above will get you started, and is sufficient for Project Euler #3. When you're ready for more, look here.
A C++ implementation using #user448810's pseudocode:
#include <iostream>
using namespace std;
void factors(long long n) {
long long z = 2;
while (z * z <= n) {
if (n % z == 0) {
cout << z << endl;
n /= z;
} else {
z++;
}
}
if (n > 1) {
cout << n << endl;
}
}
int main(int argc, char *argv[]) {
long long r = atoll(argv[1]);
factors(r);
}
// g++ factors.cpp -o factors ; factors 600851475143
Perl implementation with the same algorithm is below.
Runs ~10-15x slower (Perl 0.01 seconds for n=600851475143)
#!/usr/bin/perl
use warnings;
use strict;
sub factors {
my $n = shift;
my $z = 2;
while ($z * $z <= $n) {
if ( $n % $z ) {
$z++;
} else {
print "$z\n";
$n /= $z;
}
}
if ( $n > 1 ) {
print "$n\n"
}
}
factors(shift);
# factors 600851475143
600851475143 is outside of the range of an int
void whosprime(int x) //<-----fix heere ok?
{
bool imPrime = true;
for(int i = 1; i <= x; i++)
{...
...
Try below code:
counter = sqrt(n)
i = 2;
while (i <= counter)
if (n % i == 0)
output i
else
i++
Edit: I'm wrong (see comments). I would have deleted, but the way in which I'm wrong has helped indicate what specifically in the program takes so long to produce output, so I'll leave it :-)
This program should immediately print 1 (I'm not going to enter a debate whether that's prime or not, it's just what your program does). So if you're seeing nothing then the problem isn't execution speed, there muse be some issue with the way you're running the program.
Here is my code that worked pretty well to find the largest prime factor of any number:
#include <iostream>
using namespace std;
// --> is_prime <--
// Determines if the integer accepted is prime or not
bool is_prime(int n){
int i,count=0;
if(n==1 || n==2)
return true;
if(n%2==0)
return false;
for(i=1;i<=n;i++){
if(n%i==0)
count++;
}
if(count==2)
return true;
else
return false;
}
// --> nextPrime <--
// Finds and returns the next prime number
int nextPrime(int prime){
bool a = false;
while (a == false){
prime++;
if (is_prime(prime))
a = true;
}
return prime;
}
// ----- M A I N ------
int main(){
int value = 13195;
int prime = 2;
bool done = false;
while (done == false){
if (value%prime == 0){
value = value/prime;
if (is_prime(value)){
done = true;
}
} else {
prime = nextPrime(prime);
}
}
cout << "Largest prime factor: " << value << endl;
}
Keep in mind that if you want to find the largest prime factor of extremely large number, you have to use 'long' variable type instead of 'int' and tweak the algorithm to process faster.
short and clear vesion:
int main()
{
int MAX = 13195;
for (int i = 2; i <= MAX; i++)
{
while (MAX % i == 0)
{
MAX /= i;
cout << i << ", " << flush; // display only prime factors
}
return 0;
}
This is one of the easiest and simple-to-understand solutions of your question.
It might not be efficient like other solutions provided above but yes for those who are the beginner like me.
int main() {
int num = 0;
cout <<"Enter number\n";
cin >> num;
int fac = 2;
while (num > 1) {
if (num % fac == 0) {
cout << fac<<endl;
num=num / fac;
}
else fac++;
}
return 0;
}
# include <stdio.h>
# include <math.h>
void primeFactors(int n)
{
while (n%2 == 0)
{
printf("%d ", 2);
n = n/2;
}
for (int i = 3; i <= sqrt(n); i = i+2)
{
while (n%i == 0)
{
printf("%d ", i);
n = n/i;
}
}
if (n > 2)
printf ("%d ", n);
}
int main()
{
int n = 315;
primeFactors(n);
return 0;
}
Simple way :
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll largeFactor(ll n)
{
ll ma=0;
for(ll i=2; i*i<=n; i++)
{
while(n%i == 0)
{
n=n/i;
ma=i;
}
}
ma = max(ma, n);
return ma;
}
int main()
{
ll n;
cin>>n;
cout<<largeFactor(n)<<endl;
return 0;
}
Implementation using prime sieve ideone.
Since 600851475143 is out of scope for int as well as single long type wont work here hence here to solve we have to define our own type here with the help of typedef.
Now the range of ll is some what around 9,223,372,036,854,775,807.
typedef long long int LL
Try this code. Absolutely it's the best and the most efficient:
long long number;
bool isRepetitive;
for (int i = 2; i <= number; i++) {
isRepetitive = false;
while (number % i == 0) {
if(!isRepetitive){
cout << i << endl;
isRepetitive = true;
}
number /= i;
}
}
Enjoy! ☻