Checking if a number is a palindrome - c++

I've tried to check whether a number is a palindrome with the following code:
unsigned short digitsof (unsigned int x)
{
unsigned short n = 0;
while (x)
{
x /= 10;
n++;
}
return n;
}
bool ispalindrome (unsigned int x)
{
unsigned short digits = digitsof (x);
for (unsigned short i = 1; i <= digits / 2; i++)
{
if (x % (unsigned int)pow (10, i) != x % (unsigned int)pow (10, digits - 1 + i))
{
return false;
}
}
return true;
}
However, the following code isn't able to check for palindromes - false is always returned even if the number is a palindrome.
Can anyone point out the error?
(Please note: I'm not interested to make it into a string and reverse it to see where the problem is: rather, I'm interested to know where the error is in the above code.)

I personally would just build a string from the number, and then treat it as a normal palindrome check (check that each character in the first half matches the ones at length()-index).

x % (unsigned int)pow (10, i) is not the ith digit.

The problem is this:
x % (unsigned int)pow (10, i)
Lets try:
x =504405
i =3
SO I want 4.
x % 10^3 => 504405 %1000 => 405 NOT 4
How about
x / (unsigned int)pow (10, i -1) % 10

Just for more info! The following two functions are working for me:
double digitsof (double x)
{
double n = 0;
while (x > 1)
{
x /= 10;
n++;
}
return n;
}
bool ispalindrome (double x)
{
double digits = digitsof (x);
double temp = x;
for(double i = 1; i <= digits/2; i++)
{
float y = (int)temp % 10;
cout<<y<<endl;
temp = temp/10;
float z = (int)x / (int)pow(10 , digits - i);
cout<<(int)z<<endl;
x = (int)x % (int)pow(10 , digits - i);
if(y != z)
return false;
}
return true;
}

Code to check if given number is palindrome or not in JAVA
import java.util.*;
public class HelloWorld{
private static int countDigits(int num) {
int count = 0;
while(num>0) {
count++;
num /= 10;
}
return count;
}
public static boolean isPalin(int num) {
int digs = HelloWorld.countDigits(num);
int divderToFindMSD = 1;
int divderToFindLSD = 1;
for (int i = 0; i< digs -1; i++)
divderToFindMSD *= 10;
int mid = digs/2;
while(mid-- != 0)
{
int msd = (num/divderToFindMSD)%10;
int lsd = (num/divderToFindLSD)%10;
if(msd!=lsd)
return false;
divderToFindMSD /= 10;
divderToFindLSD *= 10;
}
return true;
}
public static void main(String []args) {
boolean isPalin = HelloWorld.isPalin(1221);
System.out.println("Results: " + isPalin);
}
}

I have done this with my own solution which is restricted with these conditions
Do not convert int to string.
Do not use any helper function.
var inputNumber = 10801
var firstDigit = 0
var lastDigit = 0
var quotient = inputNumber
while inputNumber > 0 {
lastDigit = inputNumber % 10
var tempNum = inputNumber
var count = 0
while tempNum > 0 {
tempNum = tempNum / 10
count = count + 1
}
var n = 1
for _ in 1 ..< count {
n = n * 10
}
firstDigit = quotient / n
if firstDigit != lastDigit {
print("Not a palindrome :( ")
break
}
quotient = quotient % n
inputNumber = inputNumber / 10
}
if firstDigit == lastDigit {
print("It's a palindrome :D :D ")
}

Related

STRONGN Strong Number (Special Numbers Series #2) word problem on Code Wars

Strong number is the number that the sum of the factorial of its digits is equal to number itself.
For example: 145, since
1! + 4! + 5! = 1 + 24 + 120 = 145
Here is my code, It passes most of the test except one test
#include <string>
using namespace std;
string strong_num (int number )
{
int sum = 0;
while(number != 0) {
int last = number % 10;
number /= 10;
sum+= last * (last-1);
}
if(sum == number)
return "STRONG!!!!";
else
return "Not Strong !!";
}
What is wrong with my code?
I'm surprised you're passing any test cases at all. For one thing, you are destroying number before you compare it to sum, and for another your logic is flawed.
Try this:
int factorial (int x)
{
int result = 1;
while (x > 1)
{
result *= x;
x--;
}
return result;
}
string strong_num (int number)
{
int sum = 0;
int x = number;
while (x != 0) {
int digit = x % 10;
sum += factorial (digit);
x /= 10;
}
if (sum == number)
return "STRONG!!!!";
else
return "Not Strong !!";
}
Live demo
Replace int by long long to be able to test larger numbers.
There are two problems:
first - you are changing the value of number before comparing it to sum,
second - the thing you used last * (last-1) is not a definition of factorial, the definition of factorial is factorial(x) = 1 * 2 * 3 * ... * x
int factorial (int x) {
if(x < 2) return 1;
return x * factorial(x - 1);
}
string strong_num (int number)
{
int sum = 0;
int x = number;
while (x != 0) {
int last = x % 10;
sum += factorial (last);
x /= 10;
}
if (sum == number)
return "STRONG!!!!";
else
return "Not Strong !!";
}

Function that reverse one part(half) of integer

I want to write a function to reverse one of two parts of number :
Input is: num = 1234567; part = 2
and output is: 1234765
So here is part that can be only 1 or 2
Now I know how to get part 1
int firstPartOfInt(int num) {
int ret = num;
digits = 1, halfDig = 10;
while (num > 9) {
ret = ret / 10;
digits++;
}
halfDigits = digits / 2;
for (int i = 1; i < halfDigits; i++) {
halfDigits *= 10;
}
ret = num;
while (num > halfDigits) {
ret = ret / 10;
}
return ret;
}
But I don't know how to get part 2 and reverse the number. If you post code here please do not use vector<> and other C++ feature not compatible with C
One way is to calculate the total number of digits in the number and then calculate a new number extracting digits from the original number in a certain order, complexity O(number-of-digits):
#include <stdio.h>
#include <stdlib.h>
unsigned reverse_decimal_half(unsigned n, unsigned half) {
unsigned char digits[sizeof(n) * 3];
unsigned digits10 = 0;
do digits[digits10++] = n % 10;
while(n /= 10);
unsigned result = 0;
switch(half) {
case 1:
for(unsigned digit = digits10 / 2; digit < digits10; ++digit)
result = result * 10 + digits[digit];
for(unsigned digit = digits10 / 2; digit--;)
result = result * 10 + digits[digit];
break;
case 2:
for(unsigned digit = digits10; digit-- > digits10 / 2;)
result = result * 10 + digits[digit];
for(unsigned digit = 0; digit < digits10 / 2; ++digit)
result = result * 10 + digits[digit];
break;
default:
abort();
}
return result;
}
int main() {
printf("%u %u %u\n", 0, 1, reverse_decimal_half(0, 1));
printf("%u %u %u\n", 12345678, 1, reverse_decimal_half(12345678, 1));
printf("%u %u %u\n", 12345678, 2, reverse_decimal_half(12345678, 2));
printf("%u %u %u\n", 123456789, 1, reverse_decimal_half(123456789, 1));
printf("%u %u %u\n", 123456789, 2, reverse_decimal_half(123456789, 2));
}
Outputs:
0 1 0
12345678 1 43215678
12345678 2 12348765
123456789 1 543216789
123456789 2 123459876
if understand this question well you need to reverse half of the decimal number. If the number has odd number of digits I assume that the first part is longer (for example 12345 - the first part is 123 the second 45). Because reverse is artihmetic the reverse the part 1 of 52001234 is 521234.
https://godbolt.org/z/frXvCM
(some numbers when reversed may wrap around - it is not checked)
int getndigits(unsigned number)
{
int ndigits = 0;
while(number)
{
ndigits++;
number /= 10;
}
return ndigits;
}
unsigned reverse(unsigned val, int ndigits)
{
unsigned left = 1, right = 1, result = 0;
while(--ndigits) left *= 10;
while(left)
{
result += (val / left) * right;
right *= 10;
val = val % left;
left /= 10;
}
return result;
}
unsigned reversehalf(unsigned val, int part)
{
int ndigits = getndigits(val);
unsigned parts[2], digits[2], left = 1;
if(ndigits < 3 || (ndigits == 3 && part == 2))
{
return val;
}
digits[0] = digits[1] = ndigits / 2;
if(digits[0] + digits[1] < ndigits) digits[0]++;
for(int dig = 0; dig < digits[1]; dig++) left *= 10;
parts[0] = val / left;
parts[1] = val % left;
parts[part - 1] = reverse(parts[part - 1], digits[part - 1]);
val = parts[0] * left + parts[1];
return val;
}
int main()
{
for(int number = 0; number < 40; number++)
{
unsigned num = rand();
printf("%u \tpart:%d\trev:%u\n", num,(number & 1) + 1,reversehalf(num, (number & 1) + 1));
}
}
My five cents.:)
#include <iostream>
int reverse_part_of_integer( int value, bool first_part = false )
{
const int Base = 10;
size_t n = 0;
int tmp = value;
do
{
++n;
} while ( tmp /= Base );
if ( first_part && n - n / 2 > 1 || !first_part && n / 2 > 1 )
{
n = n / 2;
int divider = 1;
while ( n-- ) divider *= Base;
int first_half = value / divider;
int second_half = value % divider;
int tmp = first_part ? first_half : second_half;
value = 0;
do
{
value = Base * value + tmp % Base;
} while ( tmp /= Base );
value = first_part ? value * divider + second_half
: first_half * divider +value;
}
return value;
}
int main()
{
int value = -123456789;
std::cout << "initial value: "
<< value << '\n';
std::cout << "First part reversed: "
<< reverse_part_of_integer( value, true ) << '\n';
std::cout << "Second part reversed: "
<< reverse_part_of_integer( value ) << '\n';
}
The program output is
initial value: -123456789
First part reversed: -543216789
Second part reversed: -123459876
Just for fun, a solution that counts only half the number of digits before reversing:
constexpr int base{10};
constexpr int partial_reverse(int number, int part)
{
// Split the number finding its "halfway"
int multiplier = base;
int abs_number = number < 0 ? -number : number;
int parts[2] = {0, abs_number};
while (parts[1] >= multiplier)
{
multiplier *= base;
parts[1] /= base;
}
multiplier /= base;
parts[0] = abs_number % multiplier;
// Now reverse only one of the two parts
int tmp = parts[part];
parts[part] = 0;
while (tmp)
{
parts[part] = parts[part] * base + tmp % base;
tmp /= base;
}
// Then rebuild the number
int reversed = parts[0] + multiplier * parts[1];
return number < 0 ? -reversed : reversed;
}
int main()
{
static_assert(partial_reverse(123, 0) == 123);
static_assert(partial_reverse(-123, 1) == -213);
static_assert(partial_reverse(1000, 0) == 1000);
static_assert(partial_reverse(1009, 1) == 109);
static_assert(partial_reverse(123456, 0) == 123654);
static_assert(partial_reverse(1234567, 0) == 1234765);
static_assert(partial_reverse(-1234567, 1) == -4321567);
}

How to get the lexical rank of a string? [duplicate]

I'm posting this although much has already been posted about this question. I didn't want to post as an answer since it's not working. The answer to this post (Finding the rank of the Given string in list of all possible permutations with Duplicates) did not work for me.
So I tried this (which is a compilation of code I've plagiarized and my attempt to deal with repetitions). The non-repeating cases work fine. BOOKKEEPER generates 83863, not the desired 10743.
(The factorial function and letter counter array 'repeats' are working correctly. I didn't post to save space.)
while (pointer != length)
{
if (sortedWordChars[pointer] != wordArray[pointer])
{
// Swap the current character with the one after that
char temp = sortedWordChars[pointer];
sortedWordChars[pointer] = sortedWordChars[next];
sortedWordChars[next] = temp;
next++;
//For each position check how many characters left have duplicates,
//and use the logic that if you need to permute n things and if 'a' things
//are similar the number of permutations is n!/a!
int ct = repeats[(sortedWordChars[pointer]-64)];
// Increment the rank
if (ct>1) { //repeats?
System.out.println("repeating " + (sortedWordChars[pointer]-64));
//In case of repetition of any character use: (n-1)!/(times)!
//e.g. if there is 1 character which is repeating twice,
//x* (n-1)!/2!
int dividend = getFactorialIter(length - pointer - 1);
int divisor = getFactorialIter(ct);
int quo = dividend/divisor;
rank += quo;
} else {
rank += getFactorialIter(length - pointer - 1);
}
} else
{
pointer++;
next = pointer + 1;
}
}
Note: this answer is for 1-based rankings, as specified implicitly by example. Here's some Python that works at least for the two examples provided. The key fact is that suffixperms * ctr[y] // ctr[x] is the number of permutations whose first letter is y of the length-(i + 1) suffix of perm.
from collections import Counter
def rankperm(perm):
rank = 1
suffixperms = 1
ctr = Counter()
for i in range(len(perm)):
x = perm[((len(perm) - 1) - i)]
ctr[x] += 1
for y in ctr:
if (y < x):
rank += ((suffixperms * ctr[y]) // ctr[x])
suffixperms = ((suffixperms * (i + 1)) // ctr[x])
return rank
print(rankperm('QUESTION'))
print(rankperm('BOOKKEEPER'))
Java version:
public static long rankPerm(String perm) {
long rank = 1;
long suffixPermCount = 1;
java.util.Map<Character, Integer> charCounts =
new java.util.HashMap<Character, Integer>();
for (int i = perm.length() - 1; i > -1; i--) {
char x = perm.charAt(i);
int xCount = charCounts.containsKey(x) ? charCounts.get(x) + 1 : 1;
charCounts.put(x, xCount);
for (java.util.Map.Entry<Character, Integer> e : charCounts.entrySet()) {
if (e.getKey() < x) {
rank += suffixPermCount * e.getValue() / xCount;
}
}
suffixPermCount *= perm.length() - i;
suffixPermCount /= xCount;
}
return rank;
}
Unranking permutations:
from collections import Counter
def unrankperm(letters, rank):
ctr = Counter()
permcount = 1
for i in range(len(letters)):
x = letters[i]
ctr[x] += 1
permcount = (permcount * (i + 1)) // ctr[x]
# ctr is the histogram of letters
# permcount is the number of distinct perms of letters
perm = []
for i in range(len(letters)):
for x in sorted(ctr.keys()):
# suffixcount is the number of distinct perms that begin with x
suffixcount = permcount * ctr[x] // (len(letters) - i)
if rank <= suffixcount:
perm.append(x)
permcount = suffixcount
ctr[x] -= 1
if ctr[x] == 0:
del ctr[x]
break
rank -= suffixcount
return ''.join(perm)
If we use mathematics, the complexity will come down and will be able to find rank quicker. This will be particularly helpful for large strings.
(more details can be found here)
Suggest to programmatically define the approach shown here (screenshot attached below) given below)
I would say David post (the accepted answer) is super cool. However, I would like to improve it further for speed. The inner loop is trying to find inverse order pairs, and for each such inverse order, it tries to contribute to the increment of rank. If we use an ordered map structure (binary search tree or BST) in that place, we can simply do an inorder traversal from the first node (left-bottom) until it reaches the current character in the BST, rather than traversal for the whole map(BST). In C++, std::map is a perfect one for BST implementation. The following code reduces the necessary iterations in loop and removes the if check.
long long rankofword(string s)
{
long long rank = 1;
long long suffixPermCount = 1;
map<char, int> m;
int size = s.size();
for (int i = size - 1; i > -1; i--)
{
char x = s[i];
m[x]++;
for (auto it = m.begin(); it != m.find(x); it++)
rank += suffixPermCount * it->second / m[x];
suffixPermCount *= (size - i);
suffixPermCount /= m[x];
}
return rank;
}
#Dvaid Einstat, this was really helpful. It took me a WHILE to figure out what you were doing as I am still learning my first language(C#). I translated it into C# and figured that I'd give that solution as well since this listing helped me so much!
Thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace CsharpVersion
{
class Program
{
//Takes in the word and checks to make sure that the word
//is between 1 and 25 charaters inclusive and only
//letters are used
static string readWord(string prompt, int high)
{
Regex rgx = new Regex("^[a-zA-Z]+$");
string word;
string result;
do
{
Console.WriteLine(prompt);
word = Console.ReadLine();
} while (word == "" | word.Length > high | rgx.IsMatch(word) == false);
result = word.ToUpper();
return result;
}
//Creates a sorted dictionary containing distinct letters
//initialized with 0 frequency
static SortedDictionary<char,int> Counter(string word)
{
char[] wordArray = word.ToCharArray();
int len = word.Length;
SortedDictionary<char,int> count = new SortedDictionary<char,int>();
foreach(char c in word)
{
if(count.ContainsKey(c))
{
}
else
{
count.Add(c, 0);
}
}
return count;
}
//Creates a factorial function
static int Factorial(int n)
{
if (n <= 1)
{
return 1;
}
else
{
return n * Factorial(n - 1);
}
}
//Ranks the word input if there are no repeated charaters
//in the word
static Int64 rankWord(char[] wordArray)
{
int n = wordArray.Length;
Int64 rank = 1;
//loops through the array of letters
for (int i = 0; i < n-1; i++)
{
int x=0;
//loops all letters after i and compares them for factorial calculation
for (int j = i+1; j<n ; j++)
{
if (wordArray[i] > wordArray[j])
{
x++;
}
}
rank = rank + x * (Factorial(n - i - 1));
}
return rank;
}
//Ranks the word input if there are repeated charaters
//in the word
static Int64 rankPerm(String word)
{
Int64 rank = 1;
Int64 suffixPermCount = 1;
SortedDictionary<char, int> counter = Counter(word);
for (int i = word.Length - 1; i > -1; i--)
{
char x = Convert.ToChar(word.Substring(i,1));
int xCount;
if(counter[x] != 0)
{
xCount = counter[x] + 1;
}
else
{
xCount = 1;
}
counter[x] = xCount;
foreach (KeyValuePair<char,int> e in counter)
{
if (e.Key < x)
{
rank += suffixPermCount * e.Value / xCount;
}
}
suffixPermCount *= word.Length - i;
suffixPermCount /= xCount;
}
return rank;
}
static void Main(string[] args)
{
Console.WriteLine("Type Exit to end the program.");
string prompt = "Please enter a word using only letters:";
const int MAX_VALUE = 25;
Int64 rank = new Int64();
string theWord;
do
{
theWord = readWord(prompt, MAX_VALUE);
char[] wordLetters = theWord.ToCharArray();
Array.Sort(wordLetters);
bool duplicate = false;
for(int i = 0; i< theWord.Length - 1; i++)
{
if(wordLetters[i] < wordLetters[i+1])
{
duplicate = true;
}
}
if(duplicate)
{
SortedDictionary<char, int> counter = Counter(theWord);
rank = rankPerm(theWord);
Console.WriteLine("\n" + theWord + " = " + rank);
}
else
{
char[] letters = theWord.ToCharArray();
rank = rankWord(letters);
Console.WriteLine("\n" + theWord + " = " + rank);
}
} while (theWord != "EXIT");
Console.WriteLine("\nPress enter to escape..");
Console.Read();
}
}
}
If there are k distinct characters, the i^th character repeated n_i times, then the total number of permutations is given by
(n_1 + n_2 + ..+ n_k)!
------------------------------------------------
n_1! n_2! ... n_k!
which is the multinomial coefficient.
Now we can use this to compute the rank of a given permutation as follows:
Consider the first character(leftmost). say it was the r^th one in the sorted order of characters.
Now if you replace the first character by any of the 1,2,3,..,(r-1)^th character and consider all possible permutations, each of these permutations will precede the given permutation. The total number can be computed using the above formula.
Once you compute the number for the first character, fix the first character, and repeat the same with the second character and so on.
Here's the C++ implementation to your question
#include<iostream>
using namespace std;
int fact(int f) {
if (f == 0) return 1;
if (f <= 2) return f;
return (f * fact(f - 1));
}
int solve(string s,int n) {
int ans = 1;
int arr[26] = {0};
int len = n - 1;
for (int i = 0; i < n; i++) {
s[i] = toupper(s[i]);
arr[s[i] - 'A']++;
}
for(int i = 0; i < n; i++) {
int temp = 0;
int x = 1;
char c = s[i];
for(int j = 0; j < c - 'A'; j++) temp += arr[j];
for (int j = 0; j < 26; j++) x = (x * fact(arr[j]));
arr[c - 'A']--;
ans = ans + (temp * ((fact(len)) / x));
len--;
}
return ans;
}
int main() {
int i,n;
string s;
cin>>s;
n=s.size();
cout << solve(s,n);
return 0;
}
Java version of unrank for a String:
public static String unrankperm(String letters, int rank) {
Map<Character, Integer> charCounts = new java.util.HashMap<>();
int permcount = 1;
for(int i = 0; i < letters.length(); i++) {
char x = letters.charAt(i);
int xCount = charCounts.containsKey(x) ? charCounts.get(x) + 1 : 1;
charCounts.put(x, xCount);
permcount = (permcount * (i + 1)) / xCount;
}
// charCounts is the histogram of letters
// permcount is the number of distinct perms of letters
StringBuilder perm = new StringBuilder();
for(int i = 0; i < letters.length(); i++) {
List<Character> sorted = new ArrayList<>(charCounts.keySet());
Collections.sort(sorted);
for(Character x : sorted) {
// suffixcount is the number of distinct perms that begin with x
Integer frequency = charCounts.get(x);
int suffixcount = permcount * frequency / (letters.length() - i);
if (rank <= suffixcount) {
perm.append(x);
permcount = suffixcount;
if(frequency == 1) {
charCounts.remove(x);
} else {
charCounts.put(x, frequency - 1);
}
break;
}
rank -= suffixcount;
}
}
return perm.toString();
}
See also n-th-permutation-algorithm-for-use-in-brute-force-bin-packaging-parallelization.

How to find the sum of elements on even position?

How to find the sum of elements on even position without usage of arrays etc, only normal operations?
For example:
159
Sum = 5.
159120
Sum = 5+1+0 = 6.
My work:
int sumofdigits(int x)
{
int sum = 0;
while(x > 0){
if (x % 100 != 0)
sum += x % 100;
x /= 100;
}
return sum;
}
Since you're counting "even" digits from the left, you first need to count the number of digits in order to know whether the least significant digit is even or not:
int sumOfEvenDigits(int x)
{
// First, count the number of digits
int digitCount = 0;
int tmp = x;
while(tmp) {
tmp /= 10;
digitCount++;
}
// If the number of digits is odd, throw away the least significant digit
if(digitCount % 2 == 1)
x /= 10;
// Keep adding the least significant digit, and throwing away two digits until you're done.
int sum = 0;
while(x){
sum += x % 10;
x /= 100;
}
return sum;
}
int accumulateIfEvenPos(int num, int pos) {
if (num == 0) return 0;
int digit = num % 10;
int next = num / 10;
return pos & 1 ? digit + accumulateIfOdd(next, ++pos) : accumulateIfOdd(next, ++pos);
}
You call it with pos 1 initially - demo here.
Well simple modification should do the trick.
int main()
{
int x = 1549;
//Get the number of digits
int length = snprintf(NULL, 0, "%i", x);
int sum = 0;
while(x > 0){
if (x % 100 != 0) {
//check if the number of digits is even to start from the last digit
if (length % 2 == 0) {
sum += x % 10;
x /= 10;
}
else {
x /= 10;
sum += x % 10;
}
x /= 10;
}
}
cout << sum << endl;
return 0;
}
EDIT: Solved the problem/bug in the algorithm. This might not be the best answer but I didn't want to completely write a different one(than the answer before edit).
You will need to have an index variable that keeps track of the position:
unsigned int digit_position = 0;
while (x > 0)
{
unsigned int digit_value = x % 10;
if (digit_position is even)
{
// Add digit_value to sum
}
// Shift value right one digit
x /= 10;
++digit_position;
}
There may be other methods using a position variable and the pow() function. But that is left as an exercise for the reader.

Miller-Rabin primality test issue in C++

I've been trying to implement the algorithm from wikipedia and while it's never outputting composite numbers as primes, it's outputting like 75% of primes as composites.
Up to 1000 it gives me this output for primes:
3, 5, 7, 11, 13, 17, 41, 97, 193, 257, 641, 769
As far as I know, my implementation is EXACTLY the same as the pseudo-code algorithm. I've debugged it line by line and it produced all of the expected variable values (I was following along with my calculator). Here's my function:
bool primeTest(int n)
{
int s = 0;
int d = n - 1;
while (d % 2 == 0)
{
d /= 2;
s++;
}
// this is the LOOP from the pseudo-algorithm
for (int i = 0; i < 10; i++)
{
int range = n - 4;
int a = rand() % range + 2;
//int a = rand() % (n/2 - 2) + 2;
bool skip = false;
long x = long(pow(a, d)) % n;
if (x == 1 || x == n - 1)
continue;
for (int r = 1; r < s; r++)
{
x = long(pow(x, 2)) % n;
if (x == 1)
{
// is not prime
return false;
}
else if (x == n - 1)
{
skip = true;
break;
}
}
if (!skip)
{
// is not prime
return false;
}
}
// is prime
return true;
}
Any help would be appreciated D:
EDIT: Here's the entire program, edited as you guys suggested - and now the output is even more broken:
bool primeTest(int n);
int main()
{
int count = 1; // number of found primes, 2 being the first of course
int maxCount = 10001;
long n = 3;
long maxN = 1000;
long prime = 0;
while (count < maxCount && n <= maxN)
{
if (primeTest(n))
{
prime = n;
cout << prime << endl;
count++;
}
n += 2;
}
//cout << prime;
return 0;
}
bool primeTest(int n)
{
int s = 0;
int d = n - 1;
while (d % 2 == 0)
{
d /= 2;
s++;
}
for (int i = 0; i < 10; i++)
{
int range = n - 4;
int a = rand() % range + 2;
//int a = rand() % (n/2 - 2) + 2;
bool skip = false;
//long x = long(pow(a, d)) % n;
long x = a;
for (int z = 1; z < d; z++)
{
x *= x;
}
x = x % n;
if (x == 1 || x == n - 1)
continue;
for (int r = 1; r < s; r++)
{
//x = long(pow(x, 2)) % n;
x = (x * x) % n;
if (x == 1)
{
return false;
}
else if (x == n - 1)
{
skip = true;
break;
}
}
if (!skip)
{
return false;
}
}
return true;
}
Now the output of primes, from 3 to 1000 (as before), is:
3, 5, 17, 257
I see now that x gets too big and it just turns into a garbage value, but I wasn't seeing that until I removed the "% n" part.
The likely source of error is the two calls to the pow function. The intermediate results will be huge (especially for the first call) and will probably overflow, causing the error. You should look at the modular exponentiation topic at Wikipedia.
Source of problem is probably here:
x = long(pow(x, 2)) % n;
pow from C standard library works on floating point numbers, so using it is a very bad idea if you just want to compute powers modulo n. Solution is really simple, just square the number by hand:
x = (x * x) % n